php获取毫秒级别时间戳及转换日期

时间:2024-03-12 07:37:06

代码如下:

public function index()
{
    $msectime = $this->getMsecTime();
    $mescdate = $this->getMsecToMescdate($msectime);
    $msectime2 = $this->getDateToMesc($mescdate);
    echo $msectime."<br />";
    echo $mescdate."<br />";
    echo $msectime2."<br />";
}

/**
 * 获取毫秒级别的时间戳
 */
public function getMsecTime()
{
    list($msec, $sec) = explode(\' \', microtime());
    $msectime =  (float)sprintf(\'%.0f\', (floatval($msec) + floatval($sec)) * 1000);
    return $msectime;
}

/**
 * 毫秒转日期
 */
public function getMsecToMescdate($msectime)
{
    $msectime = $msectime * 0.001;
    if(strstr($msectime,\'.\')){
        sprintf("%01.3f",$msectime);
        list($usec, $sec) = explode(".",$msectime);
        $sec = str_pad($sec,3,"0",STR_PAD_RIGHT);
    }else{
        $usec = $msectime;
        $sec = "000";
    }
    $date = date("Y-m-d H:i:s.x",$usec);
    return $mescdate = str_replace(\'x\', $sec, $date);
}

/**
 * 日期转毫秒
 */
public function getDateToMesc($mescdate)
{
    list($usec, $sec) = explode(".", $mescdate);
    $date = strtotime($usec);
    $return_data = str_pad($date.$sec,13,"0",STR_PAD_RIGHT);
    return $msectime = $return_data;
}

效果如图:

原文链接:https://blog.csdn.net/weixin_42330073/java/article/details/82682785