【问题标题】:date_create_from_format php on certain month and date does not return correct datedate_create_from_format php 在某个月份和日期不返回正确的日期
【发布时间】:2014-07-31 13:54:58
【问题描述】:

我在 php 中有一个函数,它使用 date_create_from_format 函数将格式为“Ym”的日期转换为日期时间。它工作正常,除了我今天发现的一种情况,我找不到问题。情况如下:

当前日期:2014 年 7 月 31 日。

$period 值:'201409'(作为我要计算的月份)

$newDateCreated = date_create_from_format('Ym', $period);

这将返回创建的新日期时间,但其值为 10/01/2014 而不是 09/01/2014

如果我没有设置值 201409,而是设置了 201411 或 201408,则正确创建了新的日期时间。

我找到的唯一解决方案是替换

$newDateCreated = date_create_from_format('Ym', $period);

$newDateCreated = date_create_from_format('Ymd', $period.'01');

我相信这必须与月份中的某天有关,但我找不到真正的问题。对此有何想法?

提前致谢。

【问题讨论】:

  • 感谢约翰,但我相信这与我没有添加或减少日期的情况不同。我只想根据给定的字符串获取日期
  • 这是同样的问题,因为它与该月的当前日期在另一个月份不存在因此被跳过这一事实有关。
  • 我刚刚收到与您提到的内容相关的解决方案。再次感谢

标签: php date datetime


【解决方案1】:

来自manual

如果格式不包含字符 !然后部分 格式中未指定的生成时间将设置为 当前系统时间。

如果格式包含字符 !,则生成的部分 未以格式提供时间,以及左侧的值 !, 将被设置为 Unix 纪元的相应值。

Unix 纪元是 1970-01-01 00:00:00 UTC。

例子

date_create_from_format('Ym', '201409');

// Tries '2014-09-31 15:59:45', but since that date doesn't exists 
// that becomes '2014-10-01':
// object(DateTime)#62 (3) {
//  ["date"] => string(19) "2014-10-01 15:59:45"
//  ["timezone_type"] => int(3)
//  ["timezone"] => string(16) "Europe/Amsterdam"
// }

date_create_from_format('!Ym', '201409');

// object(DateTime)#62 (3) {
//  ["date"] => string(19) "2014-09-01 00:00:00"
//  ["timezone_type"] => int(3)
//  ["timezone"] => string(16) "Europe/Amsterdam"
// }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-09
    • 1970-01-01
    • 2016-09-26
    • 2018-03-11
    • 1970-01-01
    • 2018-05-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多