Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
310 views
in Technique[技术] by (71.8m points)

php - Nearest next even hour

I'm looking for a way to get the nearest even hour and the associating day. Getting the hour haven't really been a problem but getting the day have been.

Technically I just need to find the next nearest even hour on the clock with the day associated to the hour, so if the next even hour is 0 then it should ahead one day, as It's the start of a new day.

Example:

It's 2014-11-08 22:05:00 -> the next nearest should then be 2014-11-09 00:00:00

It's 2014-11-08 20:35:37 -> the next nearest should then be 2014-11-08 22:00:00 (this part is easy)

What would be the easiest way to do this? This is currently what I've tried, but they've all struggled around midnight sadly

Try #1

$date = new DateTime(date('Y-m-d H:i'));
$nextDate = (intval($date->format('H'))+2) % 24;
if ($date->format('H')+2 > 24 || $nextDate == 0)
{
    if($date->format('H')+2 > 24)
        $nextDate = $date->format('H')+2 - ($date->format('H')+2 - 24);
    dd($nextDate);
    $nextDate = date('Y-m-d', strtotime("+1 days")) .' '. $nextDate . ':01';
}
else
    $nextDate = date('Y-m-d') .' '. $nextDate . ':01';

Try #2

$hours = [0=>2, 1=>2, 2=>4, 3=>4,4=>6,5=>6,6=>8,7=>8, 8=>10, 9=>10, 10=>12, 11=>12,12=>14, 13=>14,14=>16,15=>16,16=>18,17=>18, 18=>20,19=>20,20=>22, 21=>22, 22=>0,23=>0];
if ($hours[date('G')] == 0)
{
    if(date('G') != 0)
        $nextDate = date('Y-m-d') . ' ' . $hours[date('G')] . ':01:00';
    else
        $nextDate = date('Y-m-d', strtotime("+1 days")) . ' ' . $hours[date('G')] . ':01:00';
}
else
    $nextDate = date('Y-m-d') . ' ' . $hours[date('G')] . ':01:00';
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To accomplish your goal, you could add the missing time to your DateTime object:

$dt = new DateTime('2014-11-08 22:05:00');
$sec = $dt->format('G') * 3600 + $dt->format('i') * 60 + $dt->format('s');
$sec %= 7200;
$dt->modify("-$sec second")->modify('+2 hour');
echo $dt->format('c');

demo

Be careful about DST.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...