PHP 获取带毫秒的时间戳和日期时间字符串

已邀请:

dave

赞同来自:

<?php
date_default_timezone_set('PRC');
$mtimestamp = sprintf("%.3f", microtime(true)); // 带毫秒的时间戳

$timestamp = floor($mtimestamp); // 时间戳 
$milliseconds = round(($mtimestamp - $timestamp) * 1000); // 毫秒

$datetime = date("Y-m-d H:i:s", $timestamp) . '.' . $milliseconds;
echo sprintf("%s -> %s", $mtimestamp, $datetime);

输出结果:
1476673841.893 -> 2016-10-17 11:10:41.893

dave

赞同来自:

使用gettimeofday​()函数也能获取到毫秒:
<?php
date_default_timezone_set('PRC');
$timeinfo = gettimeofday();

//带毫秒的时间戳
$millisecond = sprintf("%s.d", $timeinfo["sec"], $timeinfo["usec"]/1000); 

//带毫秒的日期时间
$datetime = sprintf("%s.d", date("Y-m-d H:i:s", $timeinfo["sec"]), $timeinfo["usec"]/1000); 

echo sprintf("%s -> %s", $millisecond, $datetime);

输出结果:
1476674148.594 -> 2016-10-17 11:15:48.594

要回复问题请先登录注册