-1

我在 php 中有两个值:

值:20120101151420
20120101151306

我想从两个值中找出以秒为单位的时间差异。(我是否需要将它们转换为时间格式。如何)

4

3 回答 3

0
echo strtotime("20120101151420")- strtotime("20120101151306");

输出

74
于 2012-01-13T11:42:13.757 回答
0
function DateDiffDigit($firstdate, $seconddate)
{
    if (strlen($firstdate) != 14 || strlen($seconddate) != 14)
        return 0;

    $a = mktime( substr($firstdate, 8, 2),
                substr($firstdate, 10, 2),
                substr($firstdate, 12, 2),
                substr($firstdate, 4, 2),
                substr($firstdate, 6, 2),
                substr($firstdate, 0, 4) );

    $b = mktime( substr($seconddate, 8, 2),
                substr($seconddate, 10, 2),
                substr($seconddate, 12, 2),
                substr($seconddate, 4, 2),
                substr($seconddate, 6, 2),
                substr($seconddate, 0, 4) );

    return $b - $a;
}

$a = "20120101151420";
$b = "20120101151306";

echo DateDiffDigit($a, $b);

返回 -74 秒 ;) - 只需翻转输入/输出即可获得正值

于 2012-01-13T11:43:54.787 回答
0

在我看来,这些数字是 YYYYmmddHHMMSS 格式,因此您需要将它们转换为 unixstamps。我将使用 preg_replace 函数转换为可用于 strtotime 函数的字符串格式:

$time1 = strtotime(preg_replace('(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})', '\\1-\\2-\\3 \\4:\\5:\\6', $val1));
$time2 = strtotime(preg_replace('(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})', '\\1-\\2-\\3 \\4:\\5:\\6', $val2));

$diff = $time2 - $time1;

如果您多次使用它,编写一个转换函数会更好。

于 2012-01-13T11:53:48.987 回答