【问题标题】:How to subtract a year from leap year如何从闰年减去一年
【发布时间】:2020-02-21 15:13:13
【问题描述】:

我正在寻找以下解决方案:

$date = new DateTime('02/29/2020');
$date->sub(new DataInterval('P1Y'));
$date->format('m/d/Y');

返回:03/01/2019

有没有办法返回 02/28/2019? 谢谢

【问题讨论】:

    标签: php leap-year


    【解决方案1】:

    date('L') 如果是闰年则返回 true,因此:

    <?php
    
    $date = new DateTime('02/29/2020');
    $date->format('L') && $date->format('m-d') == '02-29' ? 'P366D' : 'P1Y';
    $date->sub(new DateInterval($interval));
    echo $date->format('m/d/Y');
    

    在这里查看https://3v4l.org/4mXX4

    【讨论】:

      【解决方案2】:

      挑战很普遍: 如果日期不跳到下个月,则在日期上加或减一个月 快到月底了。对于一年,这是加减 12 个月。

      addMonthCut() 函数的算法采用here

      function addMonthCut(DateTime $date,$month = 1) {
        $dateAdd = clone $date;
        $dateLast = clone $date;
        $strAdd = ' '.(int)$month.' Month';
        $strLast = 'last Day of '.(int)$month.' Month';
        if ($dateAdd->modify($strAdd) < $dateLast->modify($strLast)) {
          $date->modify($strAdd);
        }
        else {
          $date->modify($strLast);
        }
        return $date;
      }
      

      例子:

      $date = new DateTime('02/29/2020');
      $date = addMonthCut($date,-12);  //-1 Year
      echo $date->format('m/d/Y');  //02/28/2019
      
      $date = new DateTime('02/28/2019');
      $date = addMonthCut($date,+12);  //+1 Year
      echo $date->format('m/d/Y');  //02/28/2020
      
      $date = new DateTime('01/31/2020');
      $date = addMonthCut($date,+1);  //+1 Month
      echo $date->format('m/d/Y');  //02/29/2020
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-06-22
        • 1970-01-01
        • 2022-12-10
        • 2011-03-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多