gpt4 book ai didi

php - 为什么 'a' 和 'asdf' 被 PHP DateTime 和 strtotime 解析为有效日期?

转载 作者:可可西里 更新时间:2023-11-01 01:12:56 26 4
gpt4 key购买 nike

我正在使用 PHP 开发 Web 应用程序。我有一个日期表单,该表单正在客户端进行验证,然后通过 POST 提交以使用准备好的语句插入到数据库中。

除了客户端验证之外,我还想对日期进行服务器端验证,但我很难理解 strtotimeDateTime 的行为类。

什么规则允许这两种方法将字符串 a 转换为今天的日期以及 strtotimeasdf 转换为 1969-12-31 ?使用 date_parse 我看到 a 被识别为有效时区(不知何故),但没有与之关联的时间。 asdf 更令人困惑,因为 date_parse 实际上说 The timezone could not be found... 但它仍然出现 1969-12-31

我计划将字符串转换为日期,然后进行测试以确保日期在有效范围内,但 aasdf 都可以通过此测试。我知道我可以使用 DateTime::createFromFormat 并指定客户端代码应该发送的格式,但我真的很好奇为什么这些函数会像它们那样运行?

最佳答案

strtotime 返回 -1

strtotime 函数 - 该函数在成功时返回一个时间戳,否则返回FALSE
在 PHP 5.1.0 之前,此函数会在失败时返回 -1。

日期函数 - 该函数包含两个参数formattimestamp。现在根据时间戳整数字段,将创建日期。

因此,创建一个时间戳为 0 的日期将得到 1970-01-01,对于 -1 将得到 1969 -12-31 等等。

代码示例

echo Date('Y-m-d', 0); // OUTPUT - 1970-01-01
echo Date('Y-m-d', -1); // OUTPUT - 1969-12-31
echo Date('Y-m-d', false); // OUTPUT - 1970-01-01
echo Date('Y-m-d', strtotime('a')); // OUTPUT - 2018-01-16
echo Date('Y-m-d', strtotime('asdf')); // OUTPUT - 1970-01-01

当前场景

现在,在您的情况下,strtotime 函数似乎失败了,因此返回 -1 作为时间戳。因此日期。

引用PHP docs有关 strtotime 函数的更多信息

关于php - 为什么 'a' 和 'asdf' 被 PHP DateTime 和 strtotime 解析为有效日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48279043/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com