Using the following code to try and get 'Y-m-d', and should return 2016-05-10, but it is instead returning 2016-10-05.
// m-d-Y (Month-Day-Year)
$test_date = '05-10-2016';
// Convert to Y-m-d
$convert_date = date('Y-m-d', strtotime($test_date));
echo $convert_date;
How do I get 'Y-m-d' returned? Not trying to use explode('-', $test_date)
. Is this possible to do using proper time functions?
Yes, use DateTime
object for this:
$test_date = '05-10-2016';
$DateTime = DateTime::createFromFormat('m-d-Y', $test_date, new DateTimeZone('utc'));
var_dump($DateTime);
OUTPUT
object(DateTime)[8]
public 'date' => string '2016-05-10 15:08:53.000000' (length=26)
public 'timezone_type' => int 2
public 'timezone' => string 'UTC' (length=3)
So
echo $DateTime->format('Y-m-d'); //2016-05-10
strtotime
assume European formatted dates if they are seperated by -
and USA date format if they are seperated by /
Note: from the manual strtotime()
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. If, however, the year is given in a two digit format and the separator is a dash (-, the date string is parsed as y-m-d.
To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD) dates or DateTime::createFromFormat() when possible.
So you can just str_replace
the -
for /
// m-d-Y (Month-Day-Year)
$test_date = '05-10-2016';
$test_date = str_replace('-', '/', $test_date);
// Convert to Y-m-d
$convert_date = date('Y-m-d', strtotime($test_date));
echo $convert_date;
Or better still use the DateTime object
Note: Be aware of dates in the m/d/y or d-m-y formats; if the separator is a slash (/), then the American m/d/y is assumed. If the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed. To avoid potential errors, you should YYYY-MM-DD dates or date_create_from_format() when possible.
Source: w3schools
You have to convert '-' by '/'.
<?php// m-d-Y (Month-Day-Year)
$test_date = str_replace('-', '/', '05-10-2016');
// Convert to Y-m-d
$convert_date = date('Y-m-d', strtotime($test_date));
echo $convert_date; // 2016-05-10