PHP strtotime 不正确的转换 [英] PHP strtotime incorrect conversion

查看:32
本文介绍了PHP strtotime 不正确的转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我查看了手册,这可能是转换的怪异,但我无法弄清楚.我从用户那里获取日期并尝试在 PHP(4.1 版)中验证它(使用 strtotime 并检查返回值).用户将以欧洲格式 (d-m-y) 输入日期,但是当我将此格式日期提供给 strtotime 时,它​​是不一致的,例如:

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 转换为 2008 年 7 月 3 日

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);

第一个回声的输出是 03-01-2011(这是正确的 - 用户输入的值),第二个回声显示时间戳为 1215039600,日期回声显示 03-Jul-2008

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

推荐答案

strtotime 很神奇,但并非万无一失.如果你想保证正确的转换,你应该使用

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.

不幸的是,这只是 PHP 5.3+,而您一直停留在 4.1.甚至 strfptime() 的工作方式类似,也只出现在 5.1

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

我强烈建议您更新 PHP 版本,因为 4.x 已被弃用且不受支持.

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

话虽如此,我看不出任何类型的转换歧义如何将 2011 年转换为 2008 年.时区差异和日/月的奇怪会导致数小时和数月的时间减少,但不会改变 3 年.

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 strtotime 不正确的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆