PHP从格式创建日期方法未按预期工作
以下返回值PHP从格式创建日期方法未按预期工作,php,datetime,Php,Datetime,以下返回值false: DateTime::createFromFormat("Ymd-Gi", '20170629-902') 我已经看过了中的格式,看起来都是正确的 知道为什么吗?我认为G应该是前导零。然后0902而不是902我冒昧地查看了php源代码,找到了负责解析格式字符串的函数:。看起来是这样的, static timelib_sll timelib_get_nr_ex(char **ptr, int max_length, int *scanned_length) { ch
false
:
DateTime::createFromFormat("Ymd-Gi", '20170629-902')
我已经看过了中的格式,看起来都是正确的
知道为什么吗?我认为
G
应该是前导零。然后0902
而不是902
我冒昧地查看了php源代码,找到了负责解析格式
字符串的函数:。看起来是这样的,
static timelib_sll timelib_get_nr_ex(char **ptr, int max_length, int *scanned_length)
{
char *begin, *end, *str;
timelib_sll tmp_nr = TIMELIB_UNSET;
int len = 0;
while ((**ptr < '0') || (**ptr > '9')) {
if (**ptr == '\0') {
return TIMELIB_UNSET;
}
++*ptr;
}
begin = *ptr;
while ((**ptr >= '0') && (**ptr <= '9') && len < max_length) {
++*ptr;
++len;
}
end = *ptr;
if (scanned_length) {
*scanned_length = end - begin;
}
str = timelib_calloc(1, end - begin + 1);
memcpy(str, begin, end - begin);
tmp_nr = strtoll(str, NULL, 10);
timelib_free(str);
return tmp_nr;
}
如您所见,timelib\u get\u nr\u ex
函数不检查前导零。但是,它仍然消耗两位数。因此,在您的情况下,小时部分变成90
。然后分钟部分只剩下一个数字。但是根据格式i
,它应该是两位数的值(包括前导零)。因此,这会抛出一个错误:“找不到两位数的分钟”
要检查任何错误/警告,您可以使用
DateTime::getLastErrors()
同样对于12小时格式,他们有这样的验证
if (s->time->h > 12) {
add_pbf_error(s, "Hour can not be higher than 12", string, begin);
}
如果你用“G”或“H”,就没有什么相似的了。因此,当错误地将其解析为90
时,它不会记录错误
看起来,当只有一个数字时,不管您使用的格式值如何,您都必须使用零。但文档中说,它可以不带前导0:但显然它只适用于格式化日期,而不适用于解析日期。@Nav,是的,这有点像一个bug或文档问题。它看起来像一个PHP bug。它成功地使用
Hi
和Gi
格式说明符解析0902
,但无法使用Gi
格式说明符解析902
为09:02
。从5.4到7.1的版本没有正确解析它。
if (s->time->h > 12) {
add_pbf_error(s, "Hour can not be higher than 12", string, begin);
}