【发布时间】:2015-10-27 22:09:41
【问题描述】:
使用 DateTime 转换负日期让我误会
测试代码
var_dump(\DateTime::createFromFormat(\DateTime::ISO8601, '-0001-11-30T00:00:00+0100'));
结果
boolean false
预期结果
object(DateTime)[5]
public 'date' => string '-0001-11-30 00:00:00' (length=20)
public 'timezone_type' => int 1
public 'timezone' => string '+01:00' (length=6)
(或类似的)
附:负日期字符串是用 $d->format(\DateTime::ISO8601);
创建的PHP 版本 PHP 5.4.28
【问题讨论】:
-
为什么不直接使用
new DateTime('-0001-11-30T00:00:00+0100');?而 DateTime 类无法知道+01:00偏移量是Europe/Rome时区... -
ISO 8601 prescribes, as a minimum, a four-digit year [YYYY] to avoid the year 2000 problem. It therefore represents years from 0000 to 9999, year 0000 being equal to 1 BC and all others AD. However, years prior to 1583 are not automatically allowed by the standard. Instead "values in the range [0000] through [1582] shall only be used by mutual agreement of the partners in information interchange."[ -
所以我怀疑可能是
format()而不是createFromFormat() -
@Mark 我认为
format并不特别关心 ISO 规范。DateTime::ISO8601毕竟只是格式字符串的预设,而不是打开符合 ISO 标准的处理的标志。问题是DateTime::createFromFormat如何解析负数,或者这根本不可能? -
@Mark 就我所知,
DateTime根本不承诺任何 ISO 合规性。同样,DateTime::ISO8601只是字符串Y-m-d\TH:i:sO,仅此而已。DateTime::format('Y')会根据自己的意愿返回负值,无论 ISO 对此有何评论。