简体   繁体   English

PHP strtotime 转换不正确

[英]PHP strtotime incorrect conversion

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).我从用户那里得到一个日期,并试图在 PHP(4.1 版)中验证它(使用 strtotime 并检查返回值)。 The users will be entering the date in European format (dmy) but when I supply this format date to strtotime it is inconsistent eg:用户将以欧洲格式 (dmy) 输入日期,但是当我将此格式日期提供给 strtotime 时,它是不一致的,例如:

03-01-2011 is converted to the 3rd of July 2008 03-01-2011 转换为 2008 年 7 月 3 日

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第一个回声的 output 是 03-01-2011(这是正确的 - 用户输入的值),第二个回声显示时间戳为 1215039600,日期回声显示 03-Jul-2008

strtotime is magical, but it's not infallible. strtotime很神奇,但它并非万无一失。 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.不幸的是,这只是 PHP 5.3+,而你被困在 4.1 上。 Even strfptime() which works similary only came in at 5.1即使是strfptime()也只出现在 5.1

I'd strongly suggest updating your PHP version, as 4.x is deprecated and unsupported.我强烈建议更新您的 PHP 版本,因为 4.x 已被弃用且不受支持。

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.话虽如此,我看不出任何类型的转换歧义如何将 2011 年转换为 2008 年。时区差异和日/月奇数会影响数小时和数月,但不会在 3 年内改变。

By default PHP expects that and number-number-number is Ymd and works backwards from there until a date makes sense.默认情况下,PHP 期望 number-number-number 为 Ymd 并从那里向后工作,直到日期有意义。 You may have to change your locale setting: http://ca.php.net/manual/en/class.locale.php .您可能需要更改您的区域设置: 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.这应该可以修复欧洲日期格式错误,但请记住,现在反过来会成为问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM