2

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?

0

2 Answers 2

4

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); 
Sign up to request clarification or add additional context in comments.

5 Comments

I get this Fatal error: Call to undefined method DateTime::createFromFormat() in /home/aleckaza/public_html/tests/penny_auction/functions.php on line 17
It requires PHP 5.3+. I bet your PHP version is too old. Note that the oldest supported release is 5.3.17.
How can I do this on an older PHP?
You may have to implement it yourself, I'm afraid. Running such an old version of PHP, however, is a bad idea for a number of reasons, including security.
@Alec I've posted an alternative "old PHP" solution.
1

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 

2 Comments

Why do I need to watch out for the timezone? All I'm doing is subtracting a fixed time one second.
@Alec: Because of how 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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.