Difference between two time resulting an error

こ雲淡風輕ζ 提交于 2020-01-15 11:18:26

问题


I have this situation, i want to calculate the late of an employee and to get the late, i need to Subtract time to get the minute/hour late of an employee.

Suppose to be.. i have this code:

$time = strtotime($time_in);        
$late_time = date("H:i", strtotime('+15 minutes', $time));  

if(date("H:i:s",strtotime($time_duty[0]->time)) > $late_time ) {                
        $time_difference = (date("H:i:s",strtotime($time_duty[0]->time)) - $late_time)/60;
        print_r($time_difference);          
}

then i've encountered error

Message: A non well formed numeric value encountered


回答1:


Try this:

$time = strtotime($time_in);    
$datetime1 = new DateTime(date("H:i:s",strtotime($time_duty[0]->time)));
$datetime2 = new DateTime(date("H:i:s", strtotime('+15 minutes', $time)));
$interval = $datetime1->diff($datetime2);
echo $interval->format('H:i:s');



回答2:


You are receiving this because of this line

$time_difference = (date("H:i:s",strtotime($time_duty[0]->time)) - $late_time)/60;

As of PHP 7.1 you will get this notice when you try to do arithmetic operation on non well-formatted string like your date

 $time_difference = "2019-09-14" - "2019-09-13"; // <--- Notice as of PHP7.1

Why are you subtracting dates strings like this anyway ? You should calculate your differences using the rich class DateTime() as suggested by the earlier answer. You can also create the objects this way

$datetime1 = new DateTime( "@" . strtotime($time_duty[0]->time));
$datetime2 = new DateTime( "@" . strtotime('+15 minutes', $time));

I prefer to create DateTime objects using timestamps if I got the chance, because it will free you from the hell of timezones. Check this note from the manual

The $timezone parameter and the current timezone are ignored when the $time parameter either is a UNIX timestamp (e.g. @946684800) or specifies a timezone (e.g. 2010-01-28T15:00:00+02:00).



来源:https://stackoverflow.com/questions/57932302/difference-between-two-time-resulting-an-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!