Home > Backend Development > PHP Tutorial > PHP method example code for obtaining millisecond timestamp

PHP method example code for obtaining millisecond timestamp

怪我咯
Release: 2023-03-13 20:48:01
Original
2674 people have browsed it

这篇文章主要介绍了PHP获取毫秒级时间戳的方法,涉及php针对microtime函数返回结果的处理技巧,非常简单实用,需要的朋友可以参考下

本文实例讲述了PHP获取毫秒级时间戳的方法。分享给大家供大家参考。具体分析如下:

PHP本身没有提供获取毫秒级时间戳的函数,java里面可以通过gettime();获取。如果是要与java写的某些程序进行高精度的毫秒级的对接通信,则需要使用PHP输出毫秒级的时间。之前我采取的方法是采用不精准的方式,也就是在PHP原生的时间函数后面加上一个三位数字构成。为获取更为精准的毫秒级时间戳可以使用下面的代码:

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

/* 
     * 获取时间差,毫秒级 
     */  
      
    function get_subtraction()  
    {  
            $t1 = microtime(true);  
            $t2 = microtime(true);  
            return (($t2-$1)*1000).'ms';  
    }
    
    /* 
     * microsecond 微秒     millisecond 毫秒 
     *返回时间戳的毫秒数部分 
     */  
    function get_millisecond()  
    {  
            list($usec, $sec) = explode(" ", microtime());  
            $msec=round($usec*1000);  
            return $msec;  
               
    }  
       
    /* 
     * 
     *返回字符串的毫秒数时间戳 
     */  
    function get_total_millisecond()  
    {  
            $time = explode (" ", microtime () );   
            $time = $time [1] . ($time [0] * 1000);   
            $time2 = explode ( ".", $time );   
            $time = $time2 [0];  
            return $time;  
    }  
      
    /* 
     * 
     *返回当前 Unix 时间戳和微秒数(用秒的小数表示)浮点数表示,常用来计算代码段执行时间 
     */  
       
    function microtime_float()  
    {  
        list($usec, $sec) = explode(" ", microtime());  
        return ((float)$usec + (float)$sec);  
    }
    
    $millisecond = get_millisecond();
    $millisecond = str_pad($millisecond,3,'0',STR_PAD_RIGHT);
    echo date("YmdHis").$millisecond;
Copy after login

PS:在32位系统中php的int最大值远远小于毫秒数,所以不能使用int类型,而php中没有long类型,所以只好使用浮点数来表示。由于使用了浮点数,如果精度设置不对,使用echo显示获取的结果时可能会不正确,要想看到输出正确的结果,精度设置不能低于13位。

The above is the detailed content of PHP method example code for obtaining millisecond timestamp. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template