Ahmad Badpey
Ahmad Badpey

Reputation: 6622

How to change DateTime format to a desired format via Carbon laravel

I'm using laravel 5.5 and Carbon library to write an API.

I store all date and time values in MySQL database as common YYYY-MM-DD HH:MM:SS format.

But on the other hand front-end developer ask me to return all dates as 2017-12-20T20:30:00.000Z. seems that is a common format in JavaScript.

Is there any way to convert all DateTime formatted fields to desired format via laravel or Carbon ?

Update:
First problem is solved but another one is that client want to send date times as same 2017-12-20T20:30:00.000Z for all fields of table. while I should get and save them as common DateTime. What can I do in this case?

Upvotes: 2

Views: 3534

Answers (4)

Ali Özen
Ali Özen

Reputation: 1609

{{ date('M j, Y h:ia', strtotime($created_at)) }}

It gives us like "Dec 30, 2017 16:39am" You can edit you date time of course(M j, Y h:ia) just google it "php: date - manual"

Upvotes: 1

Milan Akabari
Milan Akabari

Reputation: 124

Laravel Provide getter and setter method for format Eloquent attribute values

by default laravel return 'dateTime' as carbon instance

so, you can change format in model using getter method

public function getDateTimeAttribute($value)
{
    $desiredFormat = "Y-M-d"; //change format as per your requirement
    $value->format($desiredFormat);
}

Link for more about getter and setter method

https://laravel.com/docs/5.5/eloquent-mutators

Upvotes: 1

Tai Le
Tai Le

Reputation: 493

Javascript uses ISO 8601 syntax. In PHP, you can use like this:

date('c', strtotime($yourDateTime));   // c is ISO 8601 format

Reference here:

Upvotes: 3

Alexey Mezenin
Alexey Mezenin

Reputation: 163978

Since the date is casting as Carbon, use format():

$date->format($desiredFormat);

The list of characters for creating $desiredFormat will also be helpful.

Upvotes: 3

Related Questions