【问题标题】:Date plus one month php [duplicate]日期加一个月php [重复]
【发布时间】:2021-05-01 18:22:14
【问题描述】:

我对 PHP 中的日期有一个小问题。

当我制作 31 + 1 月时 使用此代码

$newDate = date('Y-m-d', strtotime('31-01-2016'.' + 1 month'));
echo $newDate;

它给了我 3 月 2 日,但我需要给我 2 月 29 日,

我需要加 1 个月,而不是 30 天。

所有日期同上: 例如 1 月 1 日 + 1 个月 => 2 月 1 日

1 月 29 日 + 1 个月 => 2 月 29 日

1 月 30 日 + 1 个月 => 2 月 29 日

1 月 31 日 + 1 个月 => 2 月 29 日

感谢您的帮助

【问题讨论】:

  • 2 月 29 日距 1 月 30 日不到一个月。我没有看到问题。
  • 希望php中没有直接的函数可以实现...
  • @apokryfos 2 月是闰年的 1 个月、28 天或 29 天。
  • @Max 按照这个逻辑 05-Jan + 1 个月应该是 03-Feb。现在是 1 月,但不是 31 天。

标签: php date


【解决方案1】:

我认为您正在寻找这种类型的日期。

<?php
    $date = date('2016-01-31');
    $currentMonth = date("m",strtotime($date));
    $nextMonth = date("m",strtotime($date."+1 month"));
    if($currentMonth==$nextMonth-1 && (date("j",strtotime($date)) != date("t",strtotime($date)))){
        $nextDate = date('Y-m-d',strtotime($date." +1 month"));
    }else{
        $nextDate = date('Y-m-d', strtotime("last day of next month",strtotime($date)));
    }
    echo "Next date would be : $nextDate";
?>

查看现场演示:https://eval.in/610034

  1. 如果日期是31-01-2016,那么下一个日期是29-02-2016
  2. 如果日期是25-01-2016,那么下一个日期是25-02-2016

【讨论】:

    【解决方案2】:

    试试吧:

    $date = new DateTime('2016-01-31');
    $date->modify('last day of next month');
    

    这当然只有当你总是从一个蛾子结束到下一个蛾子结束时才算。

    【讨论】:

    • 我个人会先做一个+1 month 并检查新月份是否不是(previous+1)%12 然后再做这个。
    • @apokryfos 你是对的。那么最好使用next month,不是吗?
    • 我不认为有一个单一的计算可以得到 OP 想要的结果,因为这是一个非常不标准的事情。
    • @apokryfos 在 C# 中有方法 addDays, addMonths, addYears 在框架中构建。这不是“如此不标准的事情”。 “下个月”的想法是非常标准的。我的老板想要它,我们的客户想要它。这就是我在这里的原因。
    • @Bitterblue 通过在 1 月 31 日加上 1 个月得到 2 月 29 日是这里的不标准。
    【解决方案3】:

    试试这个,

    $date = "2016-01-29";
    $date = date('Y-m-d', strtotime("last day of next month",strtotime($date)));
    echo $date;
    

    https://3v4l.org/Y9PpV

    【讨论】:

      【解决方案4】:

      这样的事情怎么样:

      date_default_timezone_set('UTC');
      
      $current_month = (int) date('m');
      $year = date('y');
      $newDate = date('Y-m-d', strtotime('31-1-2016'.' + 1 month'));
      
      if($current_month == 12) 
      {
          $new_month=0;
          $year++;
      }
      
      $d = new DateTime( $year.'-'.($current_month+1).'-01' ); 
      echo $d->format( 'Y-m-t' )."\n";
      

      根据您的需要更改 $current_month / $year......

      【讨论】:

        猜你喜欢
        • 2012-12-19
        • 2012-11-15
        • 1970-01-01
        • 2023-01-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-14
        • 1970-01-01
        相关资源
        最近更新 更多