最近的下一个偶数小时 [英] Nearest next even hour

查看:65
本文介绍了最近的下一个偶数小时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来获得最近的偶数小时和关联日.获得一小时并不是真正的问题,但获得这一天一直是问题.

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.

从技术上讲,我只需要在时钟上找到下一个最近的偶数小时,并将日期与小时相关联,所以如果下一个偶数小时为 0,那么它应该提前一天,因为这是新一天的开始.

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.

示例:

现在是 2014-11-08 22:05:00 ->下一个最近的应该是 2014-11-09 00:00:00

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

现在是 2014-11-08 20:35:37 ->下一个最近的应该是 2014-11-08 22: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

尝试 #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';

尝试#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';

推荐答案

为了实现您的目标,您可以将缺少的时间添加到您的 DateTime 对象中:

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

演示

注意夏令时.

这篇关于最近的下一个偶数小时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆