如何在指定时间内循环日期?

时间:2018-04-05 13:12:27

标签: php

我需要根据不同的$eventname来循环日期。我已经能够编写一个脚本,在原始日期增加一周,但我不知道如何在规定的时间内循环它。

使用的代码:

    $eventname = $event->title;

    // TODO: loop for specified times if $eventname contains definded strings

    $start_date = helper('com://site/ohanah.date.format', array(
        'date' => $event->start,
        'format' => 'Y/m/d H:i',
        'timezone' => 'UTC'
    ));
    $date = strtotime($start_date) + 604800;
    echo "<pre>";
    echo date('d. F Y, H:i', $date);
    echo ' - ';
    echo helper('com://site/ohanah.date.format', array(
        'date' => $event->end,
        'format' => 'H:i',
        'timezone' => 'UTC'
    ));
    echo "</pre>";

输出:(开始日期为一周前)18. April 2018, 14:00 - 16:00

所以我的问题是,如何循环输出例如输出6次,每次间隔一周?

3 个答案:

答案 0 :(得分:2)

使用日期和时间时,不要在时间戳或类似的东西上添加秒数,因为它会让你在闰年和夏令时中遇到麻烦,因为有一天并不总是86400秒。

最好使用PHP的DateTime和DateInterval类。

<?php
$Date = new DateTime("2018-03-03 14:00:00");

for($i=0;$i<6;$i++) { //loop 6 times
    $Date->add(new DateInterval('P1W')); //add one week
    echo $Date->format("Y-m-d H:i:s").PHP_EOL;

}

输出:

2018-03-10 14:00:00
2018-03-17 14:00:00
2018-03-24 14:00:00
2018-03-31 14:00:00
2018-04-07 14:00:00

另见: http://php.net/manual/en/class.datetime.php http://php.net/manual/en/class.dateinterval.php

答案 1 :(得分:1)

那样的东西?

<?php
$oneWeek = 604800;
$date = '2018-04-05';
$dates = array($date);

for ($i = 0; $i < 6; $i++) {
    $dates[] = $date = date('Y-m-d', strtotime($date) + $oneWeek);
}

var_dump($dates);

答案 2 :(得分:0)

我并不完全确定我理解这个问题,但看起来您希望有一个条件可以为输出循环设置特定次数或确定循环是否运行了多次。

如果是这样,您可以根据条件设置计数器变量,然后运行循环次数,在您不想输出多次的情况下将计数器变量默认为1:

$eventname = $event->title;

// TODO: loop for specified times if $eventname contains definded strings
$counter = (/*your condition for $eventname*/) ? 6 : 1;
for ($x = 0; $x < $counter; $x++) {
    $start_date = helper('com://site/ohanah.date.format', array(
        'date' => $event->start,
        'format' => 'Y/m/d H:i',
        'timezone' => 'UTC'
    ));
    $date = strtotime($start_date) + 604800;
    echo "<pre>";
    echo date('d. F Y, H:i', $date);
    echo ' - ';
    echo helper('com://site/ohanah.date.format', array(
        'date' => $event->end,
        'format' => 'H:i',
        'timezone' => 'UTC'
    ));
    echo "</pre>";
}