2

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);
omrakhur
  • 1,362
  • 2
  • 24
  • 48
  • you can do this by using my solution. check the link and you can get results as you are looking. https://stackoverflow.com/questions/11176502/php-get-uk-local-time-from-server-in-different-time-zone/70781686#70781686 – pankaj Jan 20 '22 at 06:31

2 Answers2

4

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
haakym
  • 12,050
  • 12
  • 70
  • 98
  • Excellent! I am familiar with the PHP date() function and the newer DATETIME(). But I wanted to use a bit of Carbon since my application is in Laravel and it would be nice to have the security features that it provides. Thanks a million, this really helped! – omrakhur May 24 '16 at 11:29
  • 1
    @omrakhur You are more than welcome, so glad I could help out! There's a lot of functionality built into Carbon so consider diving into the docs and the source code to get more out of it. Happy coding! – haakym May 24 '16 at 12:02
1
$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');
Ben Swinburne
  • 25,669
  • 10
  • 69
  • 108