php比较小时数,在PHP中计算两个日期之间的小时数

提供另一种方法DatePeriod当使用世界协调时或格林尼治时间时区。

计数小时https://3v4l.org/Mu3HD

$start = new \DateTime('2006-04-12T12:30:00');

$end = new \DateTime('2006-04-14T11:30:00');

//determine what interval should be used - can change to weeks, months, etc

$interval = new \DateInterval('PT1H');

//create periods every hour between the two dates

$periods = new \DatePeriod($start, $interval, $end);

//count the number of objects within the periods

$hours = iterator_count($periods);

echo $hours . ' hours';

//difference between Unix Epoch

$diff = $end->getTimestamp() - $start->getTimestamp();

$hours = $diff / ( 60 * 60 );

echo $hours . ' hours (60 * 60)';

//difference between days

$diff = $end->diff($start);

$hours = $diff->h + ($diff->days * 24);

echo $hours . ' hours (days * 24)';

结果

47 hours (iterator_count)

47 hours (60 * 60)

47 hours (days * 24)

日照节数时数https://3v4l.org/QBQUB

请注意DatePeriod不包括DST的一个小时,但不增加DST结束时的另一个小时。因此,它的使用是主观的,你想要的结果和日期范围。

见电流错误报告

//set timezone to UTC to disregard daylight savings

date_default_timezone_set('America/New_York');

$interval = new \DateInterval('PT1H');

//DST starts Apr. 2nd 02:00 and moves to 03:00

$start = new \DateTime('2006-04-01T12:00:00');

$end = new \DateTime('2006-04-02T12:00:00');

$periods = new \DatePeriod($start, $interval, $end);

$hours = iterator_count($periods);

echo $hours . ' hours';

//DST ends Oct. 29th 02:00 and moves to 01:00

$start = new \DateTime('2006-10-28T12:00:00');

$end = new \DateTime('2006-10-29T12:00:00');

$periods = new \DatePeriod($start, $interval, $end);

$hours = iterator_count($periods);

echo $hours . ' hours';

结果

#2006-04-01 12:00 EST to 2006-04-02 12:00 EDT

23 hours (iterator_count)

//23 hours (60 * 60)

//24 hours (days * 24)

#2006-10-28 12:00 EDT to 2006-10-29 12:00 EST

24 hours (iterator_count)

//25 hours (60 * 60)

//24 hours (days * 24)

#2006-01-01 12:00 EST to 2007-01-01 12:00 EST

8759 hours (iterator_count)

//8760 hours (60 * 60)

//8760 hours (days * 24)

//------

#2006-04-01 12:00 UTC to 2006-04-02 12:00 UTC

24 hours (iterator_count)

//24 hours (60 * 60)

//24 hours (days * 24)

#2006-10-28 12:00 UTC to 2006-10-29 12:00 UTC

24 hours (iterator_count)

//24 hours (60 * 60)

//24 hours (days * 24)

#2006-01-01 12:00 UTC to 2007-01-01 12:00 UTC

8760 hours (iterator_count)

//8760 hours (60 * 60)

//8760 hours (days * 24)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值