我有下面的代码来计算时间差,但是当我运行代码时,它会打印0差。请在下面查看我的代码。
我想获取从PM(今天)到AM(第二天)的时间间隔的时间间隔。
//echo 'Hello World!';
//echo mktime('11','30','0','1','2019','1');
//echo mktime('12','30','0','1','2019','1');
//echo (" hello ");
//echo date(time());
//echo (" hello ");
//echo date('Y-m-d H:i:s A');
$date = "2019-10-16";
$stime = "11:30:00 PM";
$etime = "12:30:00 AM";
if("PM" == date('A', strtotime($stime)) && "AM" == date('A', strtotime($etime)))
{
//echo " Time transition ";
//get the start date and start time merging format
$sdatetime = date('Y-m-d H:i:s A', strtotime("$date $stime"));
//convert the start datetime into epoch
$startepoch = strtotime($sdatetime);
//increment the date to get the next day date
$edate = date('Y-m-d', strtotime($date. ' + 1 day'));
//get the end date and end time merged
$edatetime = date('Y-m-d H:i:s A', strtotime("$edate $etime"));
//convert the end datetime into epoch
$endepoch = strtotime($edatetime);
$timediff = ($endepoch-$startepoch)/3600.0;
echo " Time Difference: ".$timediff;
}else{
echo "No time transition";
}
// 24 hour format
//$time = "00:00:00";
//echo date('A', strtotime($time));
答案 0 :(得分:0)
PHP datetime和strtotime可以使用AM和PM解析时间。 DateTime对象也可以直接比较。 如果结束时间小于开始时间,则假定为第二天的结束时间。这比在AM和PM之间进行选择要好。
$date = "2019-10-16";
$stime = "11:30:00 PM";
$etime = "12:30:00 AM";
$dtStime = date_create($date." ".$stime);
$dtEtime = date_create($date." ".$etime);
if($dtEtime < $dtStime){
$dtEtime->modify('+1 Day');
}
$diff = $dtStime->diff($dtEtime);
$seconds = $diff->h *3600 + $diff->i * 60 + $diff->s;
echo "Diff: ".$seconds." Seconds";
返回
Diff: 3600 Seconds