Question

I have two values in php :

value: 20120101151420
20120101151306

what I am looking to figure out time diff in seconds from both values .( should I need to convert them time format .how)

Was it helpful?

Solution

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

Output

74

OTHER TIPS

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

returns -74 seconds ;) - just either flip the input/output to get a positive value

Seems to me, that the numbers are YYYYmmddHHMMSS format, so you need to convert them to unixstamps. I would use the preg_replace function to convert to string format usable for strtotime function:

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

Much better to write a function to convert if you use it more times.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top