【问题标题】:Fix year leap bug when adding month php添加月份php时修复年份跳跃错误
【发布时间】:2015-09-09 13:25:23
【问题描述】:

当日期时间对象的日期为“2012-01-30”时,我们有以下对象:

object(DateTime)#1233 (3) {
  ["date"]=>
  string(19) "2012-01-30 00:00:00"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(9) "ETC/GMT+3"
}

但是,如果加上一个月:

$date->add(new DateInterval('P1M'));

它将产生以下对象:

object(DateTime)#1233 (3) {
  ["date"]=>
  string(19) "2012-03-01 00:00:00"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(9) "ETC/GMT+3"
}

应该加上一个月,所以要显示的日期应该是 '2012-02-28',因此是 2012 年 2 月,而不是 2012 年 3 月。

我该如何解决这个问题?

【问题讨论】:

  • 请注意,这种“溢出”或“翻转”行为是设计的一部分。见it described in Example #3 in the docs。它在其他语言中也很常见,但恕我直言,这是一个糟糕的设计 - 出于您说明的原因。此外,这只是闰年问题,因为 2012 年 2 月有 29 天。对于 any 年的 any 月,这仍然是一个问题,其中生成月份的天数少于原始日期的天数。

标签: php date datetime leap-year


【解决方案1】:

试试这个

function add($date_str, $months)
{
    $date = new DateTime($date_str);
    $start_day = $date->format('j');

    $date->modify("+{$months} month");
    $end_day = $date->format('j');

    if ($start_day != $end_day)
        $date->modify('last day of last month');

    return $date;
}

$result = add('2011-01-31', 1);  // 2011-02-28

【讨论】:

  • 这是一个很好的解决方法,但我认为可能还有一种不需要格式化或自然语言解析的方法。
猜你喜欢
  • 1970-01-01
  • 2014-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-22
  • 1970-01-01
  • 1970-01-01
  • 2021-06-23
相关资源
最近更新 更多