說我有以下的字符串:減去時間字符串在PHP
$的timeleft = 0點02分30秒
我希望能夠減去1秒,把它變成00:02: 29。
我試過
$ timeLeft - 1;
但它什麼也沒做。
我該如何做到這一點,我可以從字符串中減去秒?
說我有以下的字符串:減去時間字符串在PHP
$的timeleft = 0點02分30秒
我希望能夠減去1秒,把它變成00:02: 29。
我試過
$ timeLeft - 1;
但它什麼也沒做。
我該如何做到這一點,我可以從字符串中減去秒?
需要將其轉換爲時間,減去1秒,重新格式化,例如:
$timeLeft = '00:02:30';
$time = DateTime::createFromFormat('H:i:s', $timeLeft);
$time->sub(new DateInterval('PT1S'));
$timeLeft = $time->format('H:i:s');
下面是通過將時間分成秒的情況下,PHP執行轉換「手動」髒代碼5.3+不可用。它肯定會不合適,減去的秒數大於總數。
$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);
使用strtotime
是一個很好的實用的解決方案,但你必須注意DST更改:
$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
我得到這個致命錯誤:調用未定義的方法的DateTime :: createFromFormat()在/ home第17行的/aleckaza/public_html/tests/penny_auction/functions.php – Alec
它需要PHP 5.3+。我敢打賭,你的PHP版本太舊了。請注意,最早支持的版本是5.3.17。 – Bugs
如何在舊的PHP上執行此操作? – Alec