如何在php中以hrs min sec格式獲取start_date和end_date之間的持續時間?獲取日期時間格式之間的持續時間
$start_date=2012-03-23 11:58:14 and $end_date=2012-03-24 11:54:29
如何在php中以hrs min sec格式獲取start_date和end_date之間的持續時間?獲取日期時間格式之間的持續時間
$start_date=2012-03-23 11:58:14 and $end_date=2012-03-24 11:54:29
該功能將幫助您
function datediff($interval, $datefrom, $dateto, $using_timestamps = false) {
/*
$interval can be:
yyyy - Number of full years
q - Number of full quarters
m - Number of full months
y - Difference between day numbers
(eg 1st Jan 2004 is "1", the first day. 2nd Feb 2003 is "33". The datediff is "-32".)
d - Number of full days
w - Number of full weekdays
ww - Number of full weeks
h - Number of full hours
n - Number of full minutes
s - Number of full seconds (default)
*/
使用DateTime
類:
$start_date = new DateTime('2012-03-23 11:58:14');
$end_date = new DateTime('2012-03-24 11:54:29');
$dd = date_diff($end_date, $start_date);
爲了得到小時的使用時間$dd->h
,分 - $dd->i
,秒 - $dd->s
。
echo "Hours = $dd->h, Minutes = $dd->i, Seconds = $dd->s";
我們需要格式如年月日時分秒 – Tintu 2012-04-11 05:30:35
修改答案 – 2012-04-11 05:35:23
我會
$start_time = strtotime($start_date);
$end_time = strtotime($end_date);
$difference = $end_time - $start_time;
echo date('H:i:s', $difference);
EDIT
我在假設的時間差將是小於一天犯了一個錯誤,因此,如果所述時間差大於一天,你只會看到Hours:minuetes:秒,這可能不是你想要的(如果它忽略了這個)
所以我現在要
$seconds = $difference % 60; //seconds
$difference = floor($difference/60);
$min = $difference % 60; // min
$difference = floor($difference/60);
$hours = $difference; //hours
echo "$hours : $min : $seconds";
對不起,我校
這裏你沒有考慮時區 – 2012-04-11 04:56:27
爲什麼要考慮時區,他正在計算差異 – 2012-04-11 05:45:38
這將永遠返回「23:56:15」,即使$ start_date更改爲「2012-03-22 11:58:14」(前一天) – 2012-04-11 06:23:30
看到它在這裏工作:http://codepad.viper-7.com/FPuOks
$start_date="2012-03-22 11:58:14";
$end_date="2012-03-24 11:54:29";
$start_time = strtotime($start_date);
$end_time = strtotime($end_date);
$difference = $end_time - $start_time;
echo sprintf("%02d%s%02d%s%02d", floor($difference/3600), ':', ($difference/60)%60, ':', $difference%60); // outputs 47:56:15
重複http://stackoverflow.com/questions/676824/how-to-calculate-the-difference- between-two-dates-using-php – liquorvicar 2012-04-11 06:26:35