这个问题在这里已有答案:
有2个日期(从,到),如10/1/2019和21/2/2019,如何编写一个循环来打印从2月21日到1月10日的每个日期以相反的顺序?
抱歉愚蠢的问题,但无法搞清楚!
只需遍历DateTime对象并使用while
循环输出它们。
$dt1 = new DateTime('2019-01-28');
$dt2 = new DateTime('2018-10-17');
while($dt1 >= $dt2) {
echo $dt1->format('Y-m-d') . "\r\n";
$dt1->modify('-1 day');
}
如果你想在日期之间走另一条路,只需更改日期并将modify
调用更改为+1 day
。
你也可以使用DatePeriod
:
$period = new DatePeriod(
new DateTime("10-1-2019"),
new DateInterval('P1D'),
new DateTime("21-2-2019")
);
$res = [];
foreach ($period as $key => $value) { // swap the order of the dates
array_unshift($res,$value->format('Y-m-d'));
}
这是另一种选择。 我建议您实际使用日期库,就像在其他答案中一样 - 我只想添加一个不同的方法来解决问题。
$start = '10-01-2019';
$end = '21-02-2019';
// This is to progress the range through each day.
// 24 days, 60 minutes, 60 seconds
$step = 24 * 60 * 60;
$days = array_map(function ($day) {
return date('d-M-Y', $day);
}, range(strtotime($end), strtotime($start), -$step));
我使用strtotime
函数将日转换为毫秒。
然后我从那里开始每天(24 * 60 * 60
)使用范围功能。
然后,这是一个简单的映射数组并将其转换为日期格式的情况(我使用d-M-Y
,但有more here)。