PHP DateTime :: createFromFormat返回错误的日期 [英] PHP DateTime::createFromFormat returning the wrong date
问题描述
在尝试使用太平洋/奥克兰时区和格式字符串 F-Y运行 createFromFormat
时。返回的日期是10月1日,即使我提供了 September-2019。
When trying to run createFromFormat
using the Pacific/Auckland timezone and the format string 'F-Y'. The date returned is the first of October even though I have supplied it with 'September-2019'.
我尝试在PHP 7.3.9和7.2.22上运行它
I have tried running it on PHP 7.3.9 and 7.2.22 in CLI and FPM, and online in a PHP sandbox.
<?php
echo DateTime::createFromFormat('F-Y', 'September-2019')
->setTimezone(new DateTimeZone('Pacific/Auckland'))
->format('Y-m-d');
// 2019-10-01
echo DateTime::createFromFormat('F-Y', 'September-2019')
->format('Y-m-d');
// 2019-09-01
在这两个示例中,返回日期都应具有已于2019-09-01。
In both of these examples the returned date should have been 2019-09-01. This wasn't happening yesterday.
推荐答案
之所以会出现这种情况,是因为您没有指定a的缺失部分输入到 DateTime :: createFromFormat
,它使用当前本地日期和时间的值。在奥克兰,这是10月31日,因此它尝试将日期定为2019年9月31日,即2019年10月1日。为避免此问题,请使用!
在格式字符串的开头;取而代之的是将1970年1月1日00:00:00(Unix纪元)以来的值替换为未在时间值中指定的值:
The reason for this behaviour is that when you don't specify the missing parts of a date/time input to DateTime::createFromFormat
, it uses the values from the current local date and time. In Auckland, that is October 31st and so it tries to make a date out of September 31 2019, which comes out as October 1 2019. To avoid this problem, use a !
at the start of the format string; this will instead substitute values from January 1 1970, 00:00:00 (the Unix Epoch) as required for those that are not specified in the time value:
echo DateTime::createFromFormat('!F-Y', 'September-2019')
->setTimeZone(new DateTimeZone('Pacific/Auckland'))
->format('Y-m-d');
输出:
2019-09-01
这篇关于PHP DateTime :: createFromFormat返回错误的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!