My datetimepicker is incorrectly showing a date as 20th May 2026, because it was stored in MySQL as 2016-05-26. At the moment I think this is what I should do:
$startDate = new Carbon ('d/m/Y H:i:s', $dateFromDB->startdate);
My datetimepicker is incorrectly showing a date as 20th May 2026, because it was stored in MySQL as 2016-05-26. At the moment I think this is what I should do:
$startDate = new Carbon ('d/m/Y H:i:s', $dateFromDB->startdate);
Converting twice, why?
One issue I have with your question is that you are getting the date from the DB as Y-m-d
, then converting it to d/m/Y H:i:s
then your date-picker is showing it as jS F Y
, couldn't you cut out one conversion rather than converting it twice? Something to consider.
New'ing up a Carbon Instance
If you're getting a date from the DB as Y-m-d
then you can directly pass it into the Carbon instance you are new'ing up:
$startDate = new Carbon($dateFromDB->startdate);
See the docs: http://carbon.nesbot.com/docs/#api-instantiation
Then you can use the format()
method to output the desired date format:
$startDate->format('d/m/Y H:i:s'); // 26/05/2016 09:30:05
$startDate->format('jS F Y'); // 26th May 2016
Date Mutators in Eloquent
Another approach you may consider if you are using eloquent to get the date you are transforming is to automatically cast the date to a Carbon instance by adding it to the $dates
attribute in your model.
For example if your date is start_date
in your model, you would do this:
class MyModel extends Model
{
protected $dates = ['start_date'];
}
Then you can access it directly in your code as a Carbon instance:
MyModel::first()->start_date->format('d/m/Y H:i:s');
See the docs: https://laravel.com/docs/5.2/eloquent-mutators#date-mutators
Using PHP Only
You can also use plain old PHP like this to get the date format you require:
$date = '2016-05-26 09:30:05';
$startDate = date('d/m/Y H:i:s', strtotime($date)); // 26/05/2016 09:30:05
$startDate = date('jS F Y', strtotime($date)); // 26th May 2016
$dateFromDatabase = "2016-05-20";
$dt = Carbon::createFromFormat('Y-m-d', $dateFromDatabase);
// Where js F Y results in 20th May 2016
echo $dt->format('jS F Y');