2013-04-06 50 views
1

我知道,它應該很容易,但我在PHP中的時間函數有問題。我有一個像「1小時38分鐘」的字符串,我想將它轉換爲分鐘數的整數。 任何幫助或者是微不足道的? ;)PHP:時間格式

+0

你嘗試過'preg_match'嗎? (http://php.net/preg_match) – scones 2013-04-06 16:44:22

+0

數據來自哪裏? – Cups 2013-04-06 16:47:56

+0

它來自外部來源 – Bubbleboy 2013-04-06 16:49:00

回答

4

這聽起來更像是一個sscanf然後任何時間功能的工作。

事情是這樣的:

<?php 

$input = '1 h 38 min'; 
sscanf($input, '%d h %d min', $hours, $minutes); 

$minutes += 60 * $hours; 

echo "total minutes: $minutes\n"; 
+0

謝謝,作品完美:) – Bubbleboy 2013-04-06 16:52:01

+0

如果您需要更多的靈活性,看看[DateInterval :: createFromDateString](http://www.php.net/manual/en/dateinterval.createfromdatestring。 PHP) – 2013-04-06 16:55:27

0

下面是一些代碼,更穩健一點比sscanf的和更具體一點,使用時間(以及與舊版本的PHP作品):

$input = '1 d 1 hour 38 min'; 
$usableInput = trim(str_replace(array(' y ', ' m ', ' d ', ' h ', ' s '), array(' years ', ' months ', ' days ', ' hours ', ' seconds '), " $input ")); 
$now = time(); 
$seconds = strtotime("+$usableInput", $now) - $now; 
$minutes = floor($seconds/60);