在这种情况下如何修复更正日期?

时间:2021-06-15 07:19:57

标签: php date

请告诉我,我们有一个日期,例如 2020-06-15。我需要提前一年添加一个月,并将日期更改为该月的最后一天。也就是说,结果应该是:

  • 2020-06-15(第一次约会)
  • 2020-07-31(7 月 31 天)
  • 2020-08-31(8 月 31 天)
  • 2020-09-30(9 月 30 天)
  • 2020-10-31(10 月 31 天)

依此类推,直到今年 7 月 22 日。

我是这样尝试的:

            foreach ($getDates as $getDate) {
            # Suppose getDate contains - 2020-06-15
            $firstDate = new \DateTime($getDate);
            $datesArr[] = $firstDate->format('Y-m-d');
                for ($i = 1; $i <= 12; $i++) {
                    $date = new \DateTime($getDate);

                    $month = $date->format('F');
                    $year = $date->format('Y');

                    $date->modify("+$i month");
                    # until this moment everything is fine, one by one months is added one year in advance
                    $date->modify("last day of $month $year");
                    # everything breaks here, although the documentation states "last day of July 2008"
                    $datesArr[] = $date->format('Y-m-d');
                }
        }

但是在行 modify("last day of $month $year"); 之后它不能正常工作。告诉我如何修复它?

2 个答案:

答案 0 :(得分:1)

您需要在更改日期 $month 之后而不是之前获取 $year$date->modify("+$i month"); 中的值:

<?php
$getDate = '2020-06-15';
$firstDate = new \DateTime($getDate);
$datesArr[] = $firstDate->format('Y-m-d');
for ($i = 1; $i <= 12; $i++) {
    $date = new \DateTime($getDate);

    $date->modify("+$i month");
    
    // ----- Changes here -----
    $month = $date->format('F');
    $year = $date->format('Y');
    // ------------------------
    
    $date->modify("last day of $month $year");
    
    $datesArr[] = $date->format('Y-m-d');
}
var_dump($datesArr);

这输出:

array(13) {
  [0]=>
  string(10) "2020-06-15"
  [1]=>
  string(10) "2020-07-31"
  [2]=>
  string(10) "2020-08-31"
  [3]=>
  string(10) "2020-09-30"
  [4]=>
  string(10) "2020-10-31"
  [5]=>
  string(10) "2020-11-30"
  [6]=>
  string(10) "2020-12-31"
  [7]=>
  string(10) "2021-01-31"
  [8]=>
  string(10) "2021-02-28"
  [9]=>
  string(10) "2021-03-31"
  [10]=>
  string(10) "2021-04-30"
  [11]=>
  string(10) "2021-05-31"
  [12]=>
  string(10) "2021-06-30"
}

答案 1 :(得分:0)

当使用“下个月的最后一天”这个表达时,它会变短一些。

$getDate = '2020-06-15';
$date = new \DateTime($getDate);
$datesArr[] = $date->format('Y-m-d');

for ($i = 1; $i <= 12; $i++) {
  $datesArr[] = $date
   ->modify("last day of next month")
   ->format('Y-m-d')
  ;
}

var_dump($datesArr);