PHP strtotime incorrect conversion

2019-05-23 21:33发布

问题:

I have looked in the manuals, It is probably a conversion weirdness but I cannot figure it out. I am getting a date from the user and attempting to validate it in PHP (version 4.1) (using strtotime and checking the return value). The users will be entering the date in European format (d-m-y) but when I supply this format date to strtotime it is inconsistent eg :

03-01-2011 is converted to the 3rd of July 2008

I know the manual says that a hyphen or dot separated date is interpreted as European but it is not working here.

$startDate=$_GET['start'];
echo $startDate;
$timestamp=strtotime($startDate);
echo $timestamp;
echo date("d-M-Y",$timestamp);

the output from the first echo is 03-01-2011 (this is correct - the user entered value), the second echo shews the timestamp as being 1215039600 and the date echo shews 03-Jul-2008

回答1:

strtotime is magical, but it's not infallible. If you want to guarantee a proper conversion, you should use

$dt = DateTime::CreateFromFormat('d-m-Y', $startDate);

which lets you specify explicity formats for the input so there's no ambiguity.

Unfortunately, this is PHP 5.3+ only, and you're stuck on 4.1. Even strfptime() which works similary only came in at 5.1

I'd strongly suggest updating your PHP version, as 4.x is deprecated and unsupported.

That being said, I can't see how any kind of conversion ambiguity would convert 2011 into 2008. Timezone differences and day/month oddness would throw off hours and months, but not change things by 3 years.



回答2:

By default PHP expects that and number-number-number is Y-m-d and works backwards from there until a date makes sense. You may have to change your locale setting: http://ca.php.net/manual/en/class.locale.php. This should fix the European date format error, but keep in mind that the reverse will now be a problem.



标签: php strtotime