用php创建3位数的毫秒

omqzjyyz  于 2023-02-10  发布在  PHP
关注(0)|答案(6)|浏览(126)

我有13位数字,希望创建包含毫秒的日期和时间
示例代码是这样的这是我的php脚本

$mil = 1328910295939;
$seconds = $mil / 1000;
$showdate = date('Y:m:d H:i:s', $seconds) ;

echo "$showdate";

结果是这样的2012:02:10 15:44:55.xxx ===〉xxx是我想要显示的3位毫秒。
以及如何在H:i:s后包含3位数毫秒
请帮帮我.....

vd2z7a6w

vd2z7a6w1#

像这样的怎么样?

$mil = 1328910295939;

function toTimestamp($milliseconds)
{
    $seconds = $milliseconds / 1000;
    $remainder = round($seconds - ($seconds >> 0), 3) * 1000;

    return date('Y:m:d H:i:s.', $seconds).$remainder;
}

echo toTimestamp($mil);

嗒哒!
应该也很快。
此外,以下是输出:2012:02:10 15:44:55.939-为什么你不使用-来分隔日期部分。

chy5wohz

chy5wohz2#

只需删除最后两个字符:

substr(date('Y-m-d H:i:s.u',1328910295939), 0, -2)
i2loujxw

i2loujxw3#

这里有一个函数可以精确地为你完成这个过程(通过四舍五入,而不是截断):

function getTimestamp()
{
        $microtime = floatval(substr((string)microtime(), 1, 8));
        $rounded = round($microtime, 3);
        return date("Y-m-d H:i:s") . substr((string)$rounded, 1, strlen($rounded));
}

说明:
microtime()返回2个数字作为1个字符串,由空格分隔。第二个数字是自unix纪元以来的秒数,第一个数字是自第二个数字以来的微秒数。基本上,第一个数字是以8精度格式(0.0000000)表示的微秒数,尾随的0永远不会被截断。
我们将其四舍五入到精度为3(0.00),去掉前导的0,并将其附加到实际的时间戳。
由于某种原因,php doc中的u,微秒,似乎实际上并不被支持,每次使用这个方法时,我得到的结果都是0.000,所以我求助于microtime()作为备份解决方案。

thigvfpy

thigvfpy4#

$t = 1328910295939;
echo date('Y-m-d H:i:s.', substr($t, 0, -3)) . substr($t, -3);

输出:2012-02-10 16:44:55.939(取决于时区)

qacovj5a

qacovj5a5#

因为这些答案的复杂性都很有趣,所以这里还有一个答案,它使用了提问者的原始代码,不把数字当作字符串。

$mil = 1328910295939;
$seconds = floor($mil / 1000);
$fraction = $mil % 1000;
$showdate = date('Y:m:d H:i:s',$seconds) . ".$fraction";

echo "$mil<br>
$seconds<br>
$fraction<br>
$showdate";

在设置为EST时区的服务器上输出以下内容:

1328910295939
1328910295
939
2012:02:10 16:44:55.939
jucafojl

jucafojl6#

因为我不能给@westie的函数添加注解,如果有人需要,我允许自己在他的函数中添加小数〈100时缺少的行:

$seconds = $milliseconds / 1000;
    $remainder = round($seconds - ($seconds >> 0), 3) * 1000;
    $remainder = sprintf("%03d", $remainder);
    return gmdate('H:i:s.', $seconds).$remainder;

请注意,我还使用gmdate来防止时区问题(我想您应该使用毫秒来计算持续时间,而不是日期)

相关问题