[英]Time difference using strtotime
This shouldn't be hard, but still I don't understand what is happening. 这应该不难,但我仍然不明白发生了什么。
<?php
echo date( 'H:i', strtotime( '09:00' ) - strtotime( '08:00' ) );
// returns 02:00 instead of 01:00
echo date( 'H:i', strtotime( '18:45' ) - strtotime( '17:15' ) );
// returns 02:30 instead of 01:30
echo date( 'H:i', strtotime( '17:00' ) - strtotime( '09:00' ) );
// returns 09:00 instead of 08:00
So maybe I need to add a date? 也许我需要添加日期?
<?php
echo date( 'H:i', strtotime( '22-09-2016 17:00:00' ) - strtotime( '22-09-2016 09:00:00' ) );
// still 09:00 instead of 08:00
I am using Laravel en tested in Xampp. 我在Xampp中使用Laravel测试版。
In Laravel /config/app.php 'timezone' => 'Europe/Amsterdam',
在Laravel /config/app.php'timezone'=>'Europe
'timezone' => 'Europe/Amsterdam',
In Xampp date_default_timezone_set('Europe/Amsterdam');
在Xampp
date_default_timezone_set('Europe/Amsterdam');
Still no difference. 仍然没有区别。
This calculation is done in the blade template where I cannot access the DateTime class.
此计算在刀片模板中完成,我无法访问DateTime类。
I found a way to use the DateTime class. 我找到了一种使用DateTime类的方法。 Another solution was changing the timezone to
UTC
, but then all my other timestamps are wrong. 另一个解决方案是将时区更改为
UTC
,但之后所有其他时间戳都是错误的。
find difference using DateTime object like 使用DateTime对象找到差异
$time1 = new DateTime('18:45');
$time2 = new DateTime('17:15');
$interval = $time1->diff($time2);
echo $interval->format('%H:%I');
As a purely variety alternative to the method posted by Rakesh , because you're looking at only time values rather than date values you don't need the [slight] overhead that strtotime
generates by converting everything to unix timestamps. 作为Rakesh发布的方法的纯粹替代品,因为您只查看时间值而不是日期值,因此您不需要通过将所有内容转换为unix时间戳来生成
strtotime
产生的[轻微]开销。 you also don't need to worry about time zones, as it's a purely mathematical operation. 你也不需要担心时区,因为这是一个纯粹的数学运算。
function minutes_from_time($time){
$parts = explode(":",$time);
$minutes = ($parts[0] * 60) + $parts[1];
return $minutes;
}
$timeLapsed = minutes_from_time("09:00") - minutes_from_time("08:00");
/***
Format into H:i
***/
$hours = floor($timeLapsed/60);
$minutes = $timeLapsed - ($hours * 60);
$minutes = sprintf("%02d", $minutes); //force 2 digit minutes.
$hours = sprintf("%02d", $hours); //force 2 digit hours.
$result = $hours.":".$minutes;
You may need to handle some special cases of times crossing over midnight, but.... 您可能需要处理一些跨越午夜的特殊情况,但....
If in the future you do want to include dates and/or time zone data then definitely go with using the DateTime class as recommended by myself and others. 如果您将来想要包含日期和/或时区数据,那么请务必使用我自己和其他人推荐的DateTime课程 。
Problem with timezones. 时区问题。
echo date('Y-m-d H:i:s', 0); //return "1970-01-01 01:00:00";
echo date('Y-m-d H:i:s', 3601); //return "1970-01-01 02:00:01";
use DateTime::diff
for correct work 使用
DateTime::diff
进行正确的工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.