2009-12-02 126 views

回答

32

不要落入使用日期函數這個陷阱!你在這裏有什麼是時間間隔,而不是日期。天真的辦法是做這樣的事情:

date("h:i:s.u", $mytime/1000) 

但因爲日期函數用於(哇!)日期,它不處理的時間,你會希望它在這種情況下的方式 - 它需要時區和夏令時等,格式化日期/時間。

相反,你可能只想做一些簡單的數學:

$input = 70135; 

$uSec = $input % 1000; 
$input = floor($input/1000); 

$seconds = $input % 60; 
$input = floor($input/60); 

$minutes = $input % 60; 
$input = floor($input/60); 

// and so on, for as long as you require. 
+0

我們錯了,你是對的;)++ 1 – 2009-12-02 16:37:26

+0

它仍然是一個黑客,但如果你確定你的值將少於24小時,你可以使用'gmdate()'。 – soulmerge 2009-12-02 17:23:05

+0

完美!太感謝了! – designvoid 2009-12-03 10:41:31

1

試試這個功能可以顯示毫秒的量你喜歡的方式:我相信有在PHP格式毫秒沒有內置功能

<?php 
function udate($format, $utimestamp = null) 
{ 
    if (is_null($utimestamp)) { 
     $utimestamp = microtime(true); 
    } 

    $timestamp = floor($utimestamp); 
    $milliseconds = round(($utimestamp - $timestamp) * 1000000); 

    return date(preg_replace('`(?<!\\\\)u`', sprintf("%06u", $milliseconds), $format), $timestamp); 
} 

echo udate('H:i:s.u'); // 19:40:56.78128 
echo udate('H:i:s.u', 654532123.04546); // 16:28:43.045460 
?> 

Source

+0

@Kamil的數量 - 我內聯代碼,以便它在這裏爲後人。 – 2009-12-02 16:04:54

+0

順便說一句 - 我不知道'preg_replace'在做什麼。看起來很奇怪。 – 2009-12-02 16:05:32

+1

@Dominic - 謝謝。我會在下一次做。 – 2009-12-02 16:05:56

1

,你需要使用數學。

0

由於手冊中提到:

ù微秒(在PHP加入5.2.2) 實施例:654321

我們對日期()函數

一個 'U' 參數

例子:

if(($u/60) >= 60) 
{ 
$u = mktime(0,($u/360)); 
} 
date('H:i:s',$u); 
4

如果您正在使用P- HP 5.3,你可以使用DateInterval對象:

list($seconds, $millis) = explode('.', $milliseconds/1000); 
$range = new DateInterval("PT{$seconds}S"); 
echo $range->format('%H:%I:%S') . ':' . str_pad($millis, 3, '0', STR_PAD_LEFT); 
+0

你如何獲得$秒?你必須將$ millis轉換成$秒,不是嗎? – 2009-12-02 16:21:02

+0

@daemonfire:Thx指出。現在應該工作。 – soulmerge 2009-12-02 16:24:16

+1

如果你在這裏使用70370作爲$毫秒,你會得到00:00:70:037 ...不應該70秒增加1分鐘嗎? – barfoon 2012-07-12 02:16:01

1

爲什麼用date()和格式時,你可以用數學煩惱呢? 如果$ms是您毫秒

echo floor($ms/60000).':'.floor(($ms%60000)/1000).':'.str_pad(floor($ms%1000),3,'0', STR_PAD_LEFT);