Difference between dates

前端 未结 3 389
不知归路
不知归路 2021-01-24 08:45

I want to calculate the difference between two times, one of which is the current time, and the other is just in the format HH:MM, always in the future.

If I just subtra

3条回答
  •  广开言路
    2021-01-24 09:26

    Simply add a whole day to the difference if it is negative. Assuming that $now and $futuretime are timestamps (stored in seconds since midnight), simply do the following:

    $diff = $futuretime - $now;
    if ($diff < 0)
        $diff += 24 * 3600;
    

    If they are in HH:MM format:

    list($future_hours, $future_mins) = explode(":", $futuretime);
    $futuretime = $future_hours * 60 + $future_mins;
    list($now_hours, $now_mins) = explode(":", $now);
    $now = $now_hours * 60 + $now_mins;
    $diff = $futuretime - $now;
    if ($diff < 0)
        $diff += 24 * 60;
    

    Of course the latter case returns the difference in minutes, while the former returns the difference in seconds.

    Edit: as Andy noted below in the comments, this is not a good solution if you care about changes in DST. See his solution for a better approach.

提交回复
热议问题