2015-05-10 50 views
-2

我需要做的已保存为变量,两个日期的差别:你如何将一个变量传递给strtotime?

$init = "2015-05-10 12-04-58"; 
$datetime = "2015-05-10 12-07-18"; 

然而,当我尝试使用的strtotime每个变量时间转换,既拿出空白:

$t1 = strtotime("$init"); // results in empty $t1 
$t2 = strtotime("$datetime"); // results in empty $t2 
$diff = $t2 - $t1; // some math 

我希望双引号可以做到这一点。什么不见​​了?

+1

作为一个侧面说明,为什么不使用[DATETIME](http://php.net/datetime)。 –

+1

阅读永远不会伤害:http://php.net/manual/en/function.strtotime.php – Rizier123

+0

你应该使用DateTime类。 –

回答

0

的正确方法使用日期参加工作,PHP> = 5.2.0使用DateTime,即:

date_default_timezone_set('Europe/Lisbon'); // check the list of supported timezones http://php.net/manual/en/timezones.php 

$startRaw = '2015-05-10 12-04-58'; 
$start = DateTime::createFromFormat('Y-m-d H-i-s', $startRaw); 

$endRaw = date("Y-m-d H-i-s"); 
$end = DateTime::createFromFormat('Y-m-d H-i-s', $endRaw); 

$diff = $start->diff($end); 

echo 'Difference: ' . $diff->format('%H Hours, %d days') . "\n"; 

演示:

http://ideone.com/2Tfhfo


format 

以下字符中format参数 串被识别。每个格式字符必须以百分号(%)作为前缀。

% Literal % % 
Y Years, numeric, at least 2 digits with leading 0 01, 03 
y Years, numeric 1, 3 
M Months, numeric, at least 2 digits with leading 0 01, 03, 12 
m Months, numeric 1, 3, 12 
D Days, numeric, at least 2 digits with leading 0 01, 03, 31 
d Days, numeric 1, 3, 31 
a Total amount of days 4, 18, 8123 
H Hours, numeric, at least 2 digits with leading 0 01, 03, 23 
h Hours, numeric 1, 3, 23 
I Minutes, numeric, at least 2 digits with leading 0 01, 03, 59 
i Minutes, numeric 1, 3, 59 
S Seconds, numeric, at least 2 digits with leading 0 01, 03, 57 
s Seconds, numeric 1, 3, 57 
R Sign "-" when negative, "+" when positive -, + 
r Sign "-" when negative, empty when positive -, 

了解更多关于The DateTime class

相关问题