Anonymous
22 Sep, 2018

How to get date only in desired format from created_at timestamp data in laravel?

1 Answer         27947 Views

Jiwan Thapa
22 Sep, 2018

There are a couple of ways to get date only in desired format from created_at field in laravel which are stated below.

  • Replace datatype from timestamp to string in database
  • Convert timestamp string data into array and display the first index only
  • Convert timestamp string to Unix time and get date in desired format from there.

The best option is listed first below followed by others.

Converting timestamp string to Unix format

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

Convert timestamp string data into array

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.

Replace datatype from timestamp to string in database

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.


21 Likes         0 Dislike         0 Comment        


Leave a comment