PHP strtotime returning wrong results

2019-01-29 09:19发布

问题:

strtotime('3rd January,2010') returns 1230993600 in GMT+5:30.

While according to this, unix timestamp 1230993600 is 3rd January,2009. So it's off by one year.

It's happening on PHP 5.2.6 as well as 5.2.11 .

回答1:

The problem is the , in the date string. It seems to separate date from time elements in your string, as

echo date('Y-m-d H:i:s', strtotime('3rd January, 2010'));

returns

2009-01-03 20:10:00

whereas

echo date('Y-m-d H:i:s', strtotime('3rd January 2010'));

(, removed) returns the correct date:

2010-01-03 00:00:00


回答2:

When you have a comma after the month, it assumes that 2010 is military time instead of the year. If you want it to interpret 2010 as the year, omit the comma.



回答3:

strtotime() is not infallible. It is a contextual parser that tries to convert English descriptions of a date into a timestamp. The format you are using appears to be unsuitable for proper parsing.

You can see the differences in the following examples:

echo strtotime('3rd January,2010')."<BR>";
echo strtotime('3 January, 2010')."<BR>";
echo strtotime('January 3rd, 2010')."<BR>";
echo strtotime('January 3, 2010')."<BR>";

results in:

1231042200
1231042200
1262505600
1262505600

The first two return a different timestamp than the last two. Of the formats, the last two are more semantically (English-wise) correct, and I would try to use them instead.

EDIT

As other posters have noted, the comma confuses the parser about the date portion due to the order of your date tokens.

echo strtotime('3rd January 2010')."<BR>";

returns the correct timestamp for your format.



标签: php timestamp