1 Answer 29667 Views
There are a couple of ways to get date only in desired format from created_at field in laravel which are stated below.
The best option is listed first below followed by others.
Converting timestamp string to Unix time format is the best option to get date only in desired date format from created_at field in laravel as it's easy, quick and standard method to do so. Simply, convert the created_at value back to Unix time and convert it again to desired date format using PHP date function in your frontend controller file.
$data = DB::table('tablename')->where('condition',$condition)->first(); $newtime = strtotime($data->created_at); $data->time = date('M d, Y',$newtime);
You can even use it within a loop to set new date value to all the data within the loop as shown below.
$data = DB::table('tablename')->where('condition',$condition)->get(); foreach($data as $d){ $newtime = strtotime($d->created_at); $d->time = date('M d, Y',$newtime); }
Once the value is set, you can retrieve it in blade file as shown below within the loop.
$whatever->time
You can easily convert the timestamo data in laravel to array data and then print the desired one as shown below.
// let's assume the timestamp data is 2017-12-09 09:28:06 $created_at = explode(' ','2017-12-09 09:28:06'); $created_at = $created_at[0];
You can convert the timestamp data into array using the empty space between the date and the time as the base to break the data and then set the first index of the array as the created_at value. It doesn't allow you to convert it to desired format though.
This is the basic method to get date only from database where you need to go to phpmyadmin and redefine the data type in database tables by replacing the data type form timestamp to string. If you need to make changes in all datatables, it works fine but if you need to make changes in limited number of tables then you might need to create a separate function to add data to those tables.
Let me know in the comments, which method you like or prefer. You can also let me know if you get things done some other ways because I believe each of us have a separate way of doing things and I'd love to know some more methods for the same.
Leave a comment