0

I'm trying to get time difference. This is my function, $date variable is formatted with date("d/m/Y H:i:s"); as well. But whenever I try to call function, the return variable is equal to 0. How can I fix that?

function timedifference($date){
    $old_time = strtotime($date);
    $current_time = strtotime(date("d/m/Y H:i:s"));
    $difference = $current_time - $old_time;
    return $difference;
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Lcaro
  • 45
  • 6
  • I cannot reproduce. The problem must be with the input parameter. Can you please provide an example of a value that returns 0? – El_Vanja Dec 14 '20 at 11:04
  • $date = date("d/m/Y H:i:s"); this is input parameter. – Lcaro Dec 14 '20 at 11:07
  • Then 0 is expected result, because the script will take most of the time less than one millisecond. So difference of two exact times is 0 – Pavel Janicek Dec 14 '20 at 11:09
  • I would try `var_dump($date); var_dump($old_time); var_dump($current_time);` and find out what's going on here! – Ben Hillier Dec 14 '20 at 11:15
  • I have managed to reproduce. `strtotime` cannot always parse the given format, so even with a value different than now, it fails. For example, `strtotime('16/11/2020 12:07:00')` evaluates to `false`, and so will `strtotime(date("d/m/Y H:i:s"))` whenever the day is less than 13. I suggest using `DateTime` instead. – El_Vanja Dec 14 '20 at 11:16
  • [This question](https://stackoverflow.com/questions/40905174/calculate-the-difference-between-2-timestamps-in-php) seems like it would be beneficial for your case. – El_Vanja Dec 14 '20 at 11:19
  • I guess I couldn't explain myself well.Problem is i tried to x time ago but x is never changing its always equal to 0.After 1 hour it still equal to posted 0 hour ago – Lcaro Dec 14 '20 at 11:20

2 Answers2

2

The problem is related to the strtotime function, that returns false and it gives zero return value. It's better to use DateTime object instead. Something like this.

function timediffrence($date)
{
    $old_time = \DateTime::createFromFormat('d/m/Y H:i:s', $date);
    if (!$old_time) {
        throw new \Exception('Expected input date format should be d/m/Y H:i:s');
    }

    $current_time = new \DateTime("now");

    return $current_time->getTimestamp() - $old_time->getTimestamp();
}

var_dump(timediffrence('13/12/2020 13:27:00'));
Mikhail Prosalov
  • 4,155
  • 4
  • 29
  • 41
0

replace this line

$current_time = strtotime(date("d/m/Y H:i:s"));

into

$current_time = time();

Note : time() generate current timestamp

  • This doesn't account for the problem with `$old_time = strtotime($date);`, which will return `false` in some cases. – El_Vanja Dec 14 '20 at 11:49