用PHP反复循环日期[重复]

问题描述 投票:-2回答:3

这个问题在这里已有答案:

有2个日期(从,到),如10/1/2019和21/2/2019,如何编写一个循环来打印从2月21日到1月10日的每个日期以相反的顺序?

抱歉愚蠢的问题,但无法搞清楚!

php date
3个回答
3
投票

只需遍历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');
}

工作示例:https://3v4l.org/aJ17p

如果你想在日期之间走另一条路,只需更改日期并将modify调用更改为+1 day


3
投票

你也可以使用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'));
}

0
投票

这是另一种选择。 我建议您实际使用日期库,就像在其他答案中一样 - 我只想添加一个不同的方法来解决问题。

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

https://3v4l.org/S3AK5

我使用strtotime函数将日转换为毫秒。 然后我从那里开始每天(24 * 60 * 60)使用范围功能。

然后,这是一个简单的映射数组并将其转换为日期格式的情况(我使用d-M-Y,但有more here)。

© www.soinside.com 2019 - 2024. All rights reserved.