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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…