计算下一个xx:x7的时间

时间:2013-01-01 15:28:00

标签: php date

我经常使用strtotime("next time")来获取每日活动的下一个实例的时间,但是更短的时间间隔呢?

每当分钟的单位数为7(00:0700:1700:27等等,每隔10分钟一次就会发生一些事情。

所以考虑到现在的时间,我该如何把时间花在下一个?

目前我能想出的最好的是strtotime(substr(date("Y-m-d H:i"),0,-1)."7"),但它似乎有点脏,甚至在xx:x7之前和xx:x0之前都不起作用。还有更好的方法吗?

3 个答案:

答案 0 :(得分:0)

借调DateTime

的用法
<?php
$dt = new DateTime('2013-01-01 16:54:11');
for($qq = 0; $qq < 10; ++$qq) { // loop to test all minute remainders
    $dt->modify('+1 minute +3seconds'); // seconds just for show
    $min = +$dt->format('i'); // current minutes
    $sec = +$dt->format('s'); // current seconds
    $r10 = $min % 10;
    // if it's hh:27 now, this will result in hh:37, change >= to > if that forwarding is not needed
    if($r10 >= 7) {
        $deltaMin = 17 - $r10;
    } else {
        $deltaMin = 7 - $r10;
    }
    // time left until next "good" point in time
    $change = sprintf('%+d minutes -%d seconds', $deltaMin, $sec);
    $new = clone($dt);
    $new->modify($change);
    printf("%s\t %s\n%s\n--\n", $dt->format('r'), $change, $new->format('r'));
}

答案 1 :(得分:0)

你快到了那里:

$now = time() + (date('is')>5700?600:0);
$new = strtotime(substr(date("Y-m-d H:i", $now),0,-1)."7");

答案 2 :(得分:0)

一个选项是使用DateTime::setTime()方法,稍加算术。

$date = new DateTime('12:34', new DateTimeZone('Europe/Paris'));

$minute = ceil(($date->format('i') - 7 + 1) / 10) * 10 + 7;
$date->setTime($date->format('G'), $minute, 0);

echo $date->format('H:i'); // 12:37

在循环中使用它的示例,用于演示目的:

$date = new DateTime('16:00', new DateTimeZone('Europe/Paris'));
$period = new DatePeriod($date, new DateInterval('PT1M'), 60);
foreach ($period as $date) {
    echo $date->format('H:i => ');

    $minute = ceil(($date->format('i') - 7 + 1) / 10) * 10 + 7;
    $date->setTime($date->format('G'), $minute, 0);

    echo $date->format('H:i'), PHP_EOL;
}

以上输出如下:

16:00 => 16:07
16:01 => 16:07
16:02 => 16:07
16:03 => 16:07
16:04 => 16:07
16:05 => 16:07
16:06 => 16:07
16:07 => 16:17
16:08 => 16:17
16:09 => 16:17
16:10 => 16:17
... removed to save scrolling ...
16:50 => 16:57
16:51 => 16:57
16:52 => 16:57
16:53 => 16:57
16:54 => 16:57
16:55 => 16:57
16:56 => 16:57
16:57 => 17:07
16:58 => 17:07
16:59 => 17:07
17:00 => 17:07

» See this example running online