在php的日期时间转换14位数

时间:2012-01-13 11:36:10

标签: php datetime digits

我在php中有两个值:

值: 20120101151420
20120101151306

我想要找出两个值的时间差异。(我应该将它们转换为时间格式.how)

3 个答案:

答案 0 :(得分:0)

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

输出

74

答案 1 :(得分: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秒;) - 只需翻转输入/输出以获得正值

答案 2 :(得分: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;

如果你多次使用它,写一个转换函数要好得多。