我想以 3 個月的間隔回圈一個月,請參見下面的代碼:
for($i=1; $i<=3; $i ){
$date=date('d-m-Y',strtotime("$i*3 month"));
echo "$date"."<br>";
}
但我得到以下結果:
01-01-1970
01-01-1970
01-01-1970
我想達到以下結果:
19-03-2022
19-06-2022
19-09-2022
uj5u.com熱心網友回復:
function generateDates(string $startDate, int $count): array {
$date = new DateTime($startDate);
$dates = [ $date->format('d-m-Y') ];
for ($i = 0; $i < $count - 1; $i ) {
$dateTime = $date->add(new DateInterval('P3M'));
$dates[] = $dateTime->format('d-m-Y');
}
return $dates;
}
$result = generateDates('2022-03-19', 8);
print_r($result); // This will print:
// Array
// (
// [0] => 19-03-2022
// [1] => 19-06-2022
// [2] => 19-09-2022
// [3] => 19-12-2022
// [4] => 19-03-2023
// [5] => 19-06-2023
// [6] => 19-09-2023
// [7] => 19-12-2023
// )
uj5u.com熱心網友回復:
您的主要問題是"$i*3 month"不會進行計算*3,因此這將評估"1*3 month"為strtotime. 為了解決這個問題,您必須進行計算,然后進行連接(而不是直接插值),例如:
for($i = 1; $i <= 3; $i ){
$date=date('d-m-Y',strtotime($i * 3 . " month"));
echo "$date"."<br>";
}
您可以對此進行增強,實際上strtotime有第二個引數允許您指定基本時間戳:
for($i = 0; $i < 3; $i ){
$date=date('d-m-Y',strtotime($i * 3 . " month", strtotime('2022-03-19')));
echo "$date"."<br>";
}
strtotime可能不是最好的選擇。我猜你最終想要使用的是DateTime,DateInterval并且,也許,DatePeriod
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/415519.html
標籤:
