gpt4 book ai didi

php - 如何比较自定义格式的两个时间戳?

转载 作者:行者123 更新时间:2023-12-02 22:29:22 25 4
gpt4 key购买 nike

我有两个格式如下的时间戳:substr( date( 'YmdHisu' ), 0, 17 )

20120921105240000
20120921115626000

现在,我该如何比较它们?

我试着做一个简单的方法,比如:

$diff = abs( 20120921105240000 - 20120921115626000 );

但这并没有给我所需的结果,因为时间把它搞砸了。我想做的就是找出它们之间经过了多少分钟(或秒)。

提前致谢。

最佳答案

$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;

Example

查看更多 info on the object and method .

对于 PHP < 5.3:

方法sscanf + mktime :

$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));

关于php - 如何比较自定义格式的两个时间戳?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12527375/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com