验证码: 看不清楚,换一张 查询 注册会员,免验证
  • {{ basic.site_slogan }}
  • 打开微信扫一扫,
    您还可以在这里找到我们哟

    关注我们

PHP怎么将毫秒级时间戳转为可读时间格式

阅读:1100 来源:乙速云 作者:代码code

PHP怎么将毫秒级时间戳转为可读时间格式

一、PHP 中毫秒时间戳的获取

在 PHP 中获取毫秒时间戳有许多种方法,其中一种比较通用的方法是使用 microtime() 函数获取毫秒时间戳,其返回的时间是以“秒.毫秒”为单位的浮点数。因此,我们需要对返回值进行处理,以获取完整的毫秒级时间戳。

代码示例:

function getMillisecond() {
    list($t1, $t2) = explode(' ', microtime());
    return (float)sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000);
}

这段代码将当前时间以秒.毫秒的格式进行返回,并将其转化为完整的毫秒级时间戳。

二、毫秒时间戳转化为日期时间

有了毫秒级时间戳,我们就可以将其转化为可读格式的日期时间。在 PHP 中,我们可以使用 date() 函数以及毫秒级时间戳(或以秒计算的时间戳)来格式化日期。

代码示例:

function msToTime($ms) {
    $sec = intval($ms/1000);
    $ms = $ms%1000;
    return date('Y-m-d H:i:s', time()-$sec).sprintf('.%03d', $ms);
}

该函数将毫秒级时间戳转化为人们可读的日期时间格式。其中,我们首先将毫秒级时间戳转化为秒级时间戳,然后使用 date() 函数格式化时间戳,并将微秒部分添加到输出结果中。

三、完整代码实例

下面是一个完整的示例代码,将毫秒级时间戳转化为可读的日期时间格式。

function getMillisecond() {
    list($t1, $t2) = explode(' ', microtime());
    return (float)sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000);
}

function msToTime($ms) {
    $sec = intval($ms/1000);
    $ms = $ms%1000;
    return date('Y-m-d H:i:s', time()-$sec).sprintf('.%03d', $ms);
}

$ms = getMillisecond();
echo $ms . "n";
echo msToTime($ms);

该代码的输出为:

1579670436322
2020-01-22 13:07:16.322

分享到:
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: hlamps#outlook.com (#换成@)。
相关文章
{{ v.title }}
{{ v.description||(cleanHtml(v.content)).substr(0,100)+'···' }}
你可能感兴趣
推荐阅读 更多>