在这种情况下,如何确定正确的日期



请告诉我,我们有一个日期,例如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');
}
}

但是在行修改之后("$month$year的最后一天"(;告诉我怎么修?

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

<?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"
}

当表达式"下个月的最后一天";使用。

$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);

相关内容

  • 没有找到相关文章

最新更新