【问题标题】:strtotime returns today's date for a date in wrong formatstrtotime 以错误的格式返回今天的日期
【发布时间】:2022-01-05 15:52:51
【问题描述】:

当我将“7.12.60”传递给 strtotime 时,它​​会返回今天的时间戳!我知道 strtotime 猜测给定字符串的格式,但这里的值根本不正确!它只返回今天的时间戳:

echo date( 'Y-m-d', strtotime('7.12.60') ); // outputs 2022-01-05!

我期望的是收到一个错误或正确的值,而不是一个虚构的值

【问题讨论】:

  • 60 可能会混淆它,预计是 4 位数的年份。如果您使用 1960,它可以正常工作。 Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed. If, however, the year is given in a two digit format and the separator is a dash (-), the date string is parsed as y-m-d.
  • 因为它将其转换为时间,而不是日期。试试Y-m-d H:i:s,你会得到"2022-01-05 07:13:00"——第7小时,第12分钟加上60秒变成第13分钟
  • @user335870 它将其视为没有日期的时间。在这种情况下,日期假定为今天。
  • 换句话说,它的行为就像值是7:12:60
  • 下一期,即使您将. 更改为- 并使用DateTimecreateFromFormat(),60 也将被假定为 2060 而不是 1960,因此请确保如果您以这种格式获取日期,您可能还需要在日期中添加一个世纪DEMO

标签: php datetime


【解决方案1】:

正如@aynber 和其他人的 cmets 中所提到的。它认为它是一个时间而不是日期,我在字符串的末尾添加了一个时间 (00:00:00),现在它返回 false。

非常感谢您的帮助

【讨论】:

  • 你也可以用破折号代替点,它会返回无效的日期
【解决方案2】:

您的日期拼写不清楚。 “7.12.60”应该代表什么? 2060/12/07 或 1960/12/07 或 1860/12/07?您必须提供 4 位数字的年份,以便 strtotime 正确识别。

date_create_from_format() 在这里也没有提供解决方案,因为对于 'y'(年份的两位数表示),假定它位于 1970 年到 2069 年(包括 2069 年)的范围内。

如果您需要不同的间隔来解释两位数的年份数字,则必须重新定义它并相应地修改输入。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多