代码之家  ›  专栏  ›  技术社区  ›  Guillermo

下个月,PHP中的同一天

  •  11
  • Guillermo  · 技术社区  · 17 年前

    我有一个“活动”,需要安排在每个月的同一天。

    假设您将开始日期设置为5月1日,那么接下来的活动应该在6月1日、7月1日等。问题是开始日期是31日(接下来的活动可能是30或28,具体取决于月份)。

    考虑到根据月份本身和年份的不同,有不同天数(28、30、31)的月份……有什么简单的方法来设置呢?

    考虑以下(有缺陷的)下个月功能:

    $events = array()
    
    function nextmonth($date) {
       return $date+(60*60*24*30);
    }
    $curr = $start;
    while($curr < $end) {
        $events[ = $curr;
        $curr = nextmonth($curr);
    }
    

    编辑添加:我的问题是,简单地说,如何解决任何给定月份的天数是多少,从而得到下一个相应的日期。

    16 回复  |  直到 11 年前
        1
  •  9
  •   Ionuț G. Stan    17 年前

    更新:

    这将为您提供给定月份的天数:

    echo date('t', $timestamp);
    

    date()

    我不确定您正在考虑的算法,但我相信这将帮助您:

    echo date('d-M-y', strtotime('next month'));
    
        2
  •  5
  •   Thinker    17 年前

    mktime(0,0,0,date("m")+$X,date('d'),date("Y"));

        3
  •  4
  •   Omar    8 年前

    很多时间过去了,但如果有人在搜索这个,在上面的所有答案中,我发现只有@ling答案真正回答了这个问题,但他的答案仍然不是百分之百准确,正如你在上面的结果中看到的那样,它错误地输出了年份部分。

    这是他的代码的修改版本,用于修复年份问题(我还将其修改为使用DateTime类)

      /**
       * Adding month in PHP using DateTime
       * class will render the date in a way that
       * we do not desire, for example adding one month
       * to 2018-01-31 will result in 2018-03-03 but
       * we want it to be 2018-02-28 instead.
       *
       * This method ensure that adding months
       * to a date get caculated properly.
       *
       *
       * @param DateTime $startDate
       * @param int $numberOfMonthsToAdd
       *
       * @return DateTime
       */
      function getSameDayNextMonth(DateTime $startDate, $numberOfMonthsToAdd = 1) {
        $startDateDay = (int) $startDate->format('j');
        $startDateMonth = (int) $startDate->format('n');
        $startDateYear = (int) $startDate->format('Y');
    
        $numberOfYearsToAdd = floor(($startDateMonth + $numberOfMonthsToAdd) / 12);
        if ((($startDateMonth + $numberOfMonthsToAdd) % 12) === 0) {
          $numberOfYearsToAdd--;
        }
        $year = $startDateYear + $numberOfYearsToAdd;
    
        $month = ($startDateMonth + $numberOfMonthsToAdd) % 12;
        if ($month === 0) {
          $month = 12;
        }
        $month = sprintf('%02s', $month);
    
        $numberOfDaysInMonth = (new DateTime("$year-$month-01"))->format('t');
        $day = $startDateDay;
        if ($startDateDay > $numberOfDaysInMonth) {
          $day = $numberOfDaysInMonth;
        }
        $day = sprintf('%02s', $day);
    
        return new DateTime("$year-$month-$day");
      }
    
    
      // Quick Test
      $startDate = new DateTime('2018-01-31');
      for($i=0; $i <= 40; $i++) {
        echo getSameDayNextMonth($startDate, $i)->format('Y-m-d') . "\n";
      }
    

    输出:

    2018-01-31
    2018-02-28
    2018-03-31
    2018-04-30
    2018-05-31
    2018-06-30
    2018-07-31
    2018-08-31
    2018-09-30
    2018-10-31
    2018-11-30
    2018-12-31
    2019-01-31
    2019-02-28
    2019-03-31
    2019-04-30
    2019-05-31
    2019-06-30
    2019-07-31
    2019-08-31
    2019-09-30
    2019-10-31
    2019-11-30
    2019-12-31
    2020-01-31
    2020-02-29
    2020-03-31
    2020-04-30
    2020-05-31
    2020-06-30
    2020-07-31
    2020-08-31
    2020-09-30
    2020-10-31
    2020-11-30
    2020-12-31
    2021-01-31
    2021-02-28
    2021-03-31
    2021-04-30
    2021-05-31
    
        4
  •  3
  •   Kai    14 年前

    reday 是重新加注的日期(int-月的第几天)。如果少于今天,它将 雷迪 但不超过本月的天数。如果比今天多给 雷迪 dd/mm/yyyy

    function nextrefill($reday) {
        if (date("j") < $reday) {
            $numd = date("t");
            if ($reday > $numd) {
                return str_pad($numd, 2, "0", STR_PAD_LEFT).date("/m/Y");
            } else {
                return str_pad($reday, 2, "0", STR_PAD_LEFT).date("/m/Y");
            }
        } else {
            $nextm = date('m', strtotime('first day of next month'));
            $nextmy = date('Y', strtotime('first day of next month'));
            $numd = cal_days_in_month(CAL_GREGORIAN, $nextm, $nextmy);
            if ($reday > $numd) {
                return str_pad($numd, 2, "0", STR_PAD_LEFT)."/".$nextm."/".$nextmy;
            } else {
                return str_pad($reday, 2, "0", STR_PAD_LEFT)."/".$nextm."/".$nextmy;
            }
        }
    }
    

    更直接的点(编辑)

    function nextmonthday($day) {
            $next_month = date('m', strtotime('first day of next month'));
            $year_of_next_month = date('Y', strtotime('first day of next month'));
            $no_of_day_in_next_month = cal_days_in_month(CAL_GREGORIAN, $nextm, $nextmy);
            if ($day > $no_of_day_in_next_month){
                return str_pad($no_of_day_in_next_month, 2, "0", STR_PAD_LEFT)."/".$next_month."/".$year_of_next_month;
            } else {
                return str_pad($day, 2, "0", STR_PAD_LEFT)."/".$next_month."/".$year_of_next_month;
            }
    }
    
        5
  •  2
  •   mikegreenberg    17 年前

    我建议在php.net上阅读以下评论。 strtotime() (php.net)

    编辑:下一个答案给出了我发布的链接的“摘要”,这些链接是为那些无法解读那里显示的内容的人提供的。

        6
  •  1
  •   St. John Johnson    17 年前

    June 5, 2009, next month would be July 5, 2009
    August 31, 2009, next month would be September 30, 2009
    

    或者简单地说, strtotime("+1 month")

        7
  •  1
  •   Sam Heller    16 年前

    strtotime('last day next month')
    

    因此:

    $today_next_month = strtotime('this day next month');
    $last_day_next_month = strtotime('last day next month');
    if (date('d', $today_next_month) < date('d', $last_day_next_month)){
        $date = date('m-d-Y', $last_day_next_month); 
    } else {
        $date = date('m-d-Y', $today_next_month);
    }
    echo "And the winner is : $date<br/>";
    
        8
  •  1
  •   newenglander Ck.Nitin    14 年前

    $today = new DateTime();
    $today->modify("+1 month");
    echo $today->format("d.m.Y");
    

    那么为什么不单独存储月份和日期,逐月递增,然后使用PHP的 checkdate 函数来验证日期,将日期减少一天,直到日期有效?

        9
  •  1
  •   Mihai Iorga    14 年前

    因此,与其试图计算一个月的天数(这有点复杂),不如使用当前月份轻松地找出下一个月,例如:

    date("m", strtotime($current."+1 month"));
    

    然后使用 date("d") ,并与上述代码中的下个月连接。

        10
  •  1
  •   Fábio Paiva    13 年前

    易于理解的

    public function adicionarMesMantendoDia($date, $months, $format = "Y-m-d"){
            $date = \DateTime::createFromFormat($format, $date);
    
            for($i=0;$i < $months; $i++){
                $date->modify('+ ' . date("t", $date->getTimestamp())  . ' day');
            }
            return $date;
    }
    
        11
  •  1
  •   ling    8 年前

    <?php
    function getSameDayNextMonth($time, $numberMonthsToAdd = 1)
    {
        list($year, $month, $day) = explode('-', date("Y-m-d", $time));
    
        // replace the day by one temporarily (just to make sure it exists for any month
        $numberOfYearsToAdd = floor($numberMonthsToAdd / 12);
        $year += $numberOfYearsToAdd;
        $month = ($month + $numberMonthsToAdd) % 12;
        if (0 === $month) {
            $month = 12;
        }
        $monthFormatted = sprintf('%02s', $month);
        $nbDaysInThisMonth = date("t", strtotime("$year-$monthFormatted-01"));
    
        if ((int)$day > $nbDaysInThisMonth) {
            $day = $nbDaysInThisMonth;
        }
        $day = sprintf('%02s', $day);
        return strtotime("$year-$monthFormatted-$day");
    }
    
    
    $time = strtotime("2017-10-31");
    for ($i = 0; $i <= 15; $i++) {
        $_time = getSameDayNextMonth($time, $i);
        echo date("Y-m-d", $_time) . '<br>';
    }
    
    /**
     * 2017-10-31
     * 2017-11-30
     * 2017-12-31
     * 2017-01-31
     * 2017-02-28
     * 2017-03-31
     * 2017-04-30
     * 2017-05-31
     * 2017-06-30
     * 2017-07-31
     * 2017-08-31
     * 2017-09-30
     * 2018-10-31
     * 2018-11-30
     * 2018-12-31
     * 2018-01-31
     */
    
        12
  •  0
  •   Brian Fisher    17 年前

    这个功能怎么样:

        function getNextMonthN($date, $n = 1) {
          $newDate = strtotime('+' . $n . ' months', $date);
          if (date('j', $date) !== (date('j', $newDate))) {
            $newDate = mktime(0, 0, 0, date('n', $newDate), 0, date('Y', $newDate));
          }
          return $newDate;  
        }
    

    php上还有另一个解决方案。net手动站点下的strottime条目 comments .

        13
  •  0
  •   user2503896 user2503896    11 年前

    我也有同样的问题,但当我尝试上述解决方案时,它们对我来说并不完美,我尝试了自己的方法,并提出了新的解决方案,即:

    $startDate = date("Y-m-d");
    $month = date("m",strtotime($startDate));
    $nextmonth = date("m",strtotime("$startDate +1 month"));
    if((($nextmonth-$month) > 1) || ($month == 12 && $nextmonth != 1))
    {
        $nextDate = date( 't.m.Y',strtotime("$startDate +1 week"));
    }else
    {
        $nextDate = date("Y-m-d",strtotime("$startDate +1 month"));
    }
    echo $nextSameDate = date("Y",$nextDate).'-'.date("m",$nextDate).'-'.date("d",$startDate);
    
        14
  •  0
  •   Marcelo Aymone    11 年前

    Datetime OOP样式

    <?php
    //Start Date -> 18-09-2015
    $expiry = new DateTime();
    for($i=1;$i<5;$i++){
       $expiry->modify('+1 Month');
       echo $expiry->format('d-m-Y');
       echo '<br>';
    }
    ?>
    
    //18-10-2015
    //18-11-2015
    //18-12-2015
    //18-01-2016
    
        15
  •  0
  •   Tigran Babajanyan    9 年前

    这是我用的

    这是当月日期的时间戳

    $month_timestamp = strtotime(date('Y-m', $create_timestamp));
    

    $current_day = date('d');
    

    这是下个月的同一天,格式为“Y-m-d”

    $next_month_first = date('Y-m-' . $current_day, strtotime('next month', $month_timestamp));
    
        16
  •  0
  •   AndraeRay    8 年前

    我创建了一个名为my_strotime的函数,可以处理月份的加减。它基本上是对strottime的包装。

    它检查加上或减去一个月是否可以安全地在同一天得到所需的月份。如果没有,那么它会安全地完成。

    当添加月份时,它会添加15以使您安全地进入下一个月,然后返回该月的最后一天。

    注:如前所述,本文件有效期为+1个月或-1个月

        function _my_strtotime($offset, $reference_date){
    
               //$offset is a string such as (+1 month)
    
           if(strpos($offset, 'month') === false){
             //exit if not addin/subtracing months
             return strtotime($offset, $reference_date);
           }
    
           $other_months_date = strtotime ( $offset, $reference_date );
           $day_of_other_month = date( 'd', $other_months_date );
           $day_of_reference_month = date('d', $reference_date );
    
           //check if numerical day is different. If so manipulate.
           if($day_of_reference_month != $day_of_other_month){
             if(strpos($offset, '-') === false){
               // adding months
               return strtotime('last day of this month', strtotime('+15 days', $reference_date));
             } else {
               // subtracing months
               return strtotime('-1 day', strtotime('first day of this month', $reference_date));
             }
    
           }
    
           return strtotime($offset, $reference_date);
    
         }
    
    

    测试结果:

        input=2016-01-31  (+1 month)  output=2016-02-29 //leap year
    
        input=2017-01-31  (+1 month) output=2017-02-28
    
        input=2018-05-31 (+1 month) output=2018-06-30
    
        input=2018-07-31 (-1 month) output=2018-06-30
    
        input=2016-07-22 (-1 month) output=2016-06-22
    
        input=2016-07-22 (+1 month) output=2016-08-22