Search code examples
phpstrtotime

How can subtract seconds from a time on seconds?


From a time like:

$time_on_seconds = 18000;

It is equal to 5 hours.

Now for subtract seconds Im using this code:

$new_time_on_seconds = date("H:i", strtotime($time_on_seconds) - 60);

It return me 23:59 when this should return me 4:59


Solution

  • Just remove strtotime.
    Strtotime does what the name says it takes a str (string) and makes it time (seconds) so using that on a already number won't work.

    $time_on_seconds = 18000;
    echo $new_time_on_seconds = date("H:i", $time_on_seconds - 60);
    

    But keep in mind date() is timezone aware so you may end up with a wrong result depending on your timezone.
    Set the timezone to UTC and you should get the correct result.