Say I have the following as a string:
$timeLeft = 00:02:30
I want to be able to subtract 1 second, turning it into 00:02:29.
I have tried
$timeLeft - 1;
But it does nothing.
How can I make it so I can subtract seconds from a string?
You need to convert it to a time, subtract 1 second and reformat, e.g.:
$timeLeft = '00:02:30'; $time = DateTime::createFromFormat('H:i:s', $timeLeft); $time->sub(new DateInterval('PT1S')); $timeLeft = $time->format('H:i:s'); Below is dirty code that performs the transformation "manually" by converting the time into seconds in case PHP 5.3+ is not available. It'll certainly misbehave it the number of seconds subtracted is greater than the total.
$timeLeft = '00:02:30'; list($hours, $minutes, $seconds) = explode(':', $timeLeft); $seconds += $hours*3600 + $minutes*60; unset($hours, $minutes); $seconds -= 1; //subtraction $hours = floor($seconds/3600); $seconds %= 3600; $minutes = floor($seconds/60); $seconds %= 60; $timeLeft = sprintf("%'02u:%'02u:%'02u", $hours, $minutes, $seconds); Using strtotime is a good practical solution, but you have to watch out for DST changes:
$tz = date_default_timezone_get(); // save old timezone date_default_timezone_set('UTC'); // switch to UTC echo date('H:i:s', strtotime($timeleft) - 1); // perform calculation date_default_timezone_set($tz); // restore old setting strtotime works: it parses a full date/time and gives a timestamp, which corresponds to a specific moment in time. Using it to parse input such as yours (which is not a specific moment in time but rather a duration) is not what it's for. You can adapt it, but you have to account for how it's supposed to work.