Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to convert '04-17-2013' to '2013-04-17' in PHP?

Tags:

date

php

datetime

I had the following:

$order_date = '04-17-2013';
echo $order_date . "\n";

$order_date = date_create($order_date);
$order_date = date_format($order_date, 'Y-m-d');

echo $order_date;

The output is:

before = 04-17-2013
after  = 

I thought I had that working but must have been mistaken, since it's not working now!

UPDATED WITH SOLUTION USED

$date = DateTime::createFromFormat('m-d-Y', $order_date);
$new_date = $date->format('Y-m-d');
like image 660
Peter White Avatar asked Dec 02 '25 06:12

Peter White


2 Answers

$new_date = date('Y-m-d', strtotime($order_date));

This won't work. Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed. (source)

$new_date = date_create_from_format('m-d-Y', $order_date);

or

$date = DateTime::createFromFormat('m-d-Y', $order_date);
$new_date = $date->format('Y-m-d');

See it in action

or in PHP 5.5+

$new_date = (DateTime::createFromFormat('m-d-Y', $order_date))->format('Y-m-d');
like image 145
John Conde Avatar answered Dec 03 '25 22:12

John Conde


date('Y-m-d', strtotime($order_date));
like image 20
Lance Avatar answered Dec 03 '25 22:12

Lance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!