Alec
Alec

Reputation: 177

Subtract Time String in PHP

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?

Upvotes: 2

Views: 3456

Answers (2)

Bugs
Bugs

Reputation: 1452

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);

Upvotes: 4

Jon
Jon

Reputation: 437904

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

Upvotes: 1

Related Questions