I have this code:
$endDate='02-20-2014'; //Just updated this
echo date('Y-d-m',strtotime($endDate));
Why does strtotime()
keeps giving me 1969-31-12
?
My goal is to get: 2014-02-20
I have this code:
$endDate='02-20-2014'; //Just updated this
echo date('Y-d-m',strtotime($endDate));
Why does strtotime()
keeps giving me 1969-31-12
?
My goal is to get: 2014-02-20
The root problem
PHP supported date formats do not include the input date format you're using, '02-20-2014'
or mm-DD-YY
Why you are getting 1969-31-12
Since your input format is wrong, strtotime()
fails. In PHP 5.1 and above, strtotime()
would have returned false
in this case and the date()
call would have evaluated to 1970-01-01
(i.e the day of the UNIX epoch).
However, in your case strtotime()
seems to return -1
on failure instead. This indicates you're using an outdated version of PHP (5.0.x or less). It also causes the date()
call to return 1969-31-12
(i.e minus one second of the UNIX epoch)
The solution
Change your input date format to any of the PHP supported date formats. In addition, in order to get the output date format you indicate, 2014-02-20
or YY-mm-dd
, you should adjust the format
argument of the date()
function in accordance from Y-d-m
to Y-m-d
.
For example:
$endDate='2014-20-02';
echo date('Y-m-d',strtotime($endDate));
Side note about the PHP version
If possible, it's highly recommended that you migrate your system from the outdated PHP 5.0.x version to the latest versions. You should be careful to check the change logs of each version migration ever since to make sure you're not breaking any exiting code.
Just found this and thought I should add a correction and additional information:
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: Converting string to Date and DateTime)
If using strtotime
then 02-20-2014 != 02/20/2014
02-20-2014 will fail as there is no 20th month
02/20/2014 is 20th February
If you use the a year first format as detailed above eg
$endDate='2014-20-02';
then the middle pair of numbers is always a month so this date is invalid whether your dates are American or European.
echo date('Y-m-d',strtotime($endDate));
and
echo date('Y-d-m',strtotime($endDate));
will both fail as the first parameter passed to date is the output format and strtotime
will already have failed leading to a returned date of "1969-12-31"