我的时差公式工作,但只有当开始时间低于结束时间。
当结束时间转到第二天,它就不再工作了。请看下面的例子。
比如说,我的大学从下午2点工作到下午4点。<——这个管用,差2个小时。
比如说,我的大学从晚上11点工作到凌晨3点。<——这不起作用,它给出8小时的差值。
$to_time = strtotime("2008-12-13 22:00:00");
$from_time = strtotime("2008-12-13 03:00:00");
$hourdiff = round(abs($to_time - $from_time) / 3600,2). " uur";
echo "<td>".$hourdiff."</td>";
我看到的问题是你没有改变日期时间
比如说,我的大学从晚上11点工作到凌晨3点。<——这不起作用,它给出8小时的差值。
我能看到的最可能的解释是你在做这样的事情:
$to_time = strtotime("2008-12-13 11:00:00");
$from_time = strtotime("2008-12-13 03:00:00");
这是错误的,因为11pm不是11:00:00,而是23:00:00。代码应该像这样:
$to_time = strtotime("2008-12-13 22:00:00");
$from_time = strtotime("2008-12-13 03:00:00");
如果是第二天凌晨3点,那么应该是这样的:
$to_time = strtotime("2008-12-13 22:00:00");
$from_time = strtotime("2008-12-14 03:00:00");
你可以试试这个
$date1 = "2014-05-27 01:00:00";
$date2 = "2014-05-28 02:00:00";
$timestamp1 = strtotime($date1);
$timestamp2 = strtotime($date2);
echo "Difference between two dates is " . $hour = abs($timestamp2 - $timestamp1)/(60*60) . " hour(s)";
我已经找到了答案,那就写一个if语句。
$from_time = strtotime("2008-12-12 22:00:00");
$to_time = strtotime("2008-12-12 23:00:00");
if ($to_time<$from_time){
$to_time_past = strtotime("2008-12-13 01:00:00");
$hourdiff = round(abs($to_time_past - $from_time) / 3600,2). " uur";
}else{
$hourdiff = round(abs($to_time - $from_time) / 3600,2). " uur";
}