标准功能(请参阅codepad)
<?php
$start_time_o = "18:00";
$end_time_o = date("H:i");
function get_time_difference(){
global $start_time_o, $end_time_o;
$start_time = explode(":", $start_time_o);
$end_time = explode(":", $end_time_o);
$start_time_stamp = mktime($start_time[0], $start_time[1], 0, 0, 0, 0);
$end_time_stamp = mktime($end_time[0], $end_time[1], 0, 0, 0, 0);
$time_difference = $end_time_stamp - $start_time_stamp;
return gmdate("H:i", $time_difference);
}
echo get_time_difference();
?>
修改后的功能(请参阅codepad)
<?php
$start_time_o = "18:00:01";
$end_time_o = date("H:i:s");
function get_time_difference(){
global $start_time_o, $end_time_o;
$start_time = explode(":", $start_time_o);
$end_time = explode(":", $end_time_o);
$start_time_stamp = mktime($start_time[0], $start_time[1], $start_time[2], 0, 0, 0, 0);
$end_time_stamp = mktime($end_time[0], $end_time[1], $end_time[2], 0, 0, 0, 0);
$time_difference = $end_time_stamp - $start_time_stamp;
return gmdate("H:i:s", $time_difference);
}
echo get_time_difference();
?>
第一个功能没有任何错误或通知。
修改后的函数给出了消息:
Deprecated: mktime(): The is_dst parameter is deprecated in C:\xampp\htdocs\index.php on line 13
Deprecated: mktime(): The is_dst parameter is deprecated in C:\xampp\htdocs\index.php on line 14
我不知道为什么我只在修改过的功能中收到消息? 这里有什么不对?
答案 0 :(得分:3)
如果您想使用更简单的方法,请尝试使用DateTime::diff
<?php
$datetime1 = new DateTime('18:00:01');
$datetime2 = new DateTime();
$interval = $datetime1->diff($datetime2);
echo $interval->format('H:i:s');
?>
这是一个可以让您更容易使用的功能:
<?php
function diff($first_datetime, $second_datetime = "now")
{
$datetime1 = new DateTime($first_datetime);
$datetime2 = new DateTime($second_datetime);
$interval = $datetime1->diff($datetime2);
return $interval->format('H:i:s');
}
// One of the date/time parameters is now so
// we only have to pass one parameter
echo diff('18:00:01');
// Neither parameter is now
echo diff('18:00:01', '20:00:00');
?>
答案 1 :(得分:2)
使用strtotime
像
$someString = '10/10/2012 4:34 pm';
date_default_timezone_set('American/New_York');
$timestamp = strtotime($someString);
echo date('Y/m/d H:i:s', $timestamp);
答案 2 :(得分:2)
您在mktime()
函数上使用了太多参数。删除其中一个零,如下所示:
$start_time_stamp = mktime($start_time[0], $start_time[1], $start_time[2], 0, 0, 0);
$end_time_stamp = mktime($end_time[0], $end_time[1], $end_time[2], 0, 0, 0);
这是导致你的问题的原因,但正如@NullPointer在他的回答中指出的那样,有一种更有效,更好的方法来实现这一目标。使用他的解决方案!