Strange behavior of PHP time math: Why is strtotime() returning negative numbers?

前端 未结 5 921
星月不相逢
星月不相逢 2020-12-12 00:51

I\'m trying to do some very basic time math - basically, given inputs of time and distance, calculate the speed. I chose to use strtotime() to convert the time inputs into s

5条回答
  •  佛祖请我去吃肉
    2020-12-12 01:43

    strtotime() without a second argument gets the time from the supplied string and fills in the blanks from the current date:

    echo date('Y-m-d H:i:s', strtotime("3:15:00"));
    -> 2009-06-30 03:15:00
    

    With a second argument it calculates the date relative to the second argument:

    echo date('Y-m-d H:i:s', strtotime("3:15:00", 0));
    -> 1970-01-01 03:15:00
    

    To calculate the difference between two timestamps in seconds, you can just do this:

    echo strtotime("3:15:00") - strtotime("3:00:00");
    -> 900
    

    Edit: Of course taking into account which is the bigger number:

    $t1 = strtotime("3:15:00");
    $t2 = strtotime("3:30:00");
    
    $diff = max($t1, $t2) - min($t1, $t2);
    $diff = abs($t1 - $t2);
    

    Or something of that nature...

提交回复
热议问题