我有两个时间戳形式如下:substr( date( 'YmdHisu' ), 0, 17 )
20120921105240000
20120921115626000
现在,我如何比较它们?
我尝试做一个简单的方法,如:
$diff = abs( 20120921105240000 - 20120921115626000 );
但这并没有给我所需的结果,因为时间会把它搞得一团糟。我想做的就是找出它们之间经过了多少分钟(或几秒钟)。
提前致谢。
答案 0 :(得分:6)
$date1 = DateTime::createFromFormat('Ymdhisu', '20120921105240000');
$date2 = DateTime::createFromFormat('Ymdhisu', '20120921115626000');
$interval = $date1->diff($date2);
print_r($interval);
/*DateInterval Object
(
[y] => 0
[m] => 0
[d] => 0
[h] => 1
[i] => 3
[s] => 46
[invert] => 0
[days] => 0
)*/
$seconds = $date2->getTimestamp()-$date1->getTimestamp();
echo $seconds;
请参见附加info on the object and method。
对于PHP< 5.3:
$date1 = '20120921105240000';
$date2 = '20120921115626000';
function parse_mydate_string($string) {
if ($a = sscanf($string, '%4s%2s%2s%2s%2s%2s') {
if (FALSE !== $r = mktime($a[3], $a[4], $a[5], $a[1], $a[2], $a[0])) {
return $r;
}
}
throw new InvalidArgumentException('Not the expect date string.');
}
$diff = parse_mydate_string($date1) - parse_mydate_string($date2);
$absdiff = abs($diff);
或sscanf
+ vsprintf
+ strtotime
:
$date1 = '20120921105240000';
$date2 = '20120921115626000';
$date1 = vsprintf('%s-%s-%s %s:%s:%s', sscanf($date1, '%4s%2s%2s%2s%2s%2s'));
$date2 = vsprintf('%s-%s-%s %s:%s:%s', sscanf($date2, '%4s%2s%2s%2s%2s%2s'));
$diff = abs(strtotime($date2) - strtotime($date1));
或多个substr
字符串操作+ strtotime
:
$date1 = '20120921105240000';
$date2 = '20120921115626000';
$date1 = substr($date1, 0, 4).'-'.substr($date1, 4, 2).'-'.substr($date1, 6, 2).' '.substr($date1, 8, 2).':'.substr($date1, 10, 2).':'.substr($date1, 12, 2);
$date2 = substr($date2, 0, 4).'-'.substr($date2, 4, 2).'-'.substr($date2, 6, 2).' '.substr($date2, 8, 2).':'.substr($date2, 10, 2).':'.substr($date2, 12, 2);
$diff = abs(strtotime($date2) - strtotime($date1));
答案 1 :(得分:0)
最好使用标准的日期/时间格式,以避免从头开始完成所有工作。
看看这里的讨论: PHP How to find the time elapsed since a date time?
答案 2 :(得分:-1)
尝试使用strcmp
,当然更好的方法是在比较之前将其转换为Datetime对象