Jaan
Jaan

Reputation: 251

Php subtracts second from digit

How is it possible using php to substract seconds from a Digit time?

How example if I have this time:

00:01:30

and I want to subtract this by 3 second which would make this

00:01:27

Upvotes: 0

Views: 48

Answers (3)

kchason
kchason

Reputation: 2885

As mentioned in the other answers, the DateTime class is very helpful and has more flexibility with formats and such. However, for this isolated example, it can be done as:

$time = '00:01:30';
echo date('H:i:s', strtotime($time .' - 3 seconds'));

Which produces: 00:01:27

Edit:

Per the comment about microseconds, the date function does not support this.

Microseconds (added in PHP 5.2.2). Note that date() will always generate 000000 since it takes an integer parameter, whereas DateTime::format() does support microseconds if DateTime was created with microseconds.

As stated above, and in the other answers, the DateTime class in PHP is much more flexible for formatting dates. It allows for timezone support with setTimezone and multiple input formats with createFromFormat.

Upvotes: 0

Ant Avison
Ant Avison

Reputation: 178

Use the modify function to subtract the seconds, as below.

$timeStr = new DateTime("09:00:00");

$timeStr->modify('-3 seconds'); // can be seconds, hours.. etc

echo $timeStr->format('H:i:s');

Answer borrowed from Add 30 seconds to the time with PHP

Upvotes: 1

IsThisJavascript
IsThisJavascript

Reputation: 1716

You should check out the DateTime class. It's really powerful and a godsend.

<?php     
$date = new DateTime("2017-11-20 00:01:30");
$date->modify("-3 seconds");
echo $date->format("H:i:s");
//output :00:01:27

Upvotes: 1

Related Questions