2009-12-02 125 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);