PHP strtotime 转换不正确
我查看了手册,这可能是一个转换怪异,但我无法弄清楚。我从用户那里获取一个日期并尝试在 PHP(版本 4.1)中验证它(使用 strtotime 并检查返回值)。用户将以欧洲格式(dmy)输入日期,但是当我向 strtotime 提供此格式日期时,它是不一致的,例如:
03-01-2011 转换为 2008 年 7 月 3 日
我知道手册上说连字符或点分隔日期被解释为欧洲日期,但在这里不起作用。
$startDate=$_GET['start'];
echo $startDate;
$timestamp=strtotime($startDate);
echo $timestamp;
echo date("d-M-Y",$timestamp);
第一个回显的输出是 03-01-2011(这是正确的 - 用户输入的值),第二个回显显示时间戳为 1215039600,日期回显显示 03-Jul-2008
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
strtotime
很神奇,但它并非绝对可靠。如果您想保证正确的转换,您应该使用它来为输入指定明确的格式,这样就不会出现歧义。
不幸的是,这仅限于 PHP 5.3+,而您只能使用 4.1。即使工作原理类似的
strfptime()
也只在 5.1 版本中出现,我强烈建议更新您的 PHP 版本,因为 4.x 已被弃用且不受支持。
话虽这么说,我看不出任何类型的转换歧义如何将 2011 年转换为 2008 年。时区差异和日/月奇数会导致数小时和数月的偏差,但不会改变 3 年。
strtotime
is magical, but it's not infallible. If you want to guarantee a proper conversion, you should usewhich 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.1I'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.
默认情况下,PHP 认为 number-number-number 是 Ymd,并从那里向后计算,直到日期有意义。您可能需要更改您的区域设置: http://ca.php.net/手册/en/class.locale.php。这应该可以修复欧洲日期格式错误,但请记住,相反的情况现在将成为问题。
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.