Home  >  Article  >  php教程  >  PHP获取毫秒时间戳,php获取毫秒

PHP获取毫秒时间戳,php获取毫秒

WBOY
WBOYOriginal
2016-06-13 09:10:45659browse

PHP获取毫秒时间戳,php获取毫秒

我们知道,PHP中time()函数获取的时间戳,其单位是秒.

但是,前端JS获取的时间戳,单位是毫秒. 那么,在实际应用中,如何将JS和PHP的时间戳统一,即如何使用PHP获取毫秒时间戳呢,请看下例: php //函数,获取毫秒时间戳 function getMillisecond() { list($t1, $t2) = explode(' ', microtime()); return (float)sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000); }   //上面的函数是百度出来的,我刚开始看着也不是很明白. //现分开详细讲解如下: function getMillisecond_new(){ //使用microtime()获取微秒时间戳,格式(中间空格隔开):'秒的小数部分 秒的整数部分',例如'0.69718900 1420440552' //将微秒字符串explode炸开,接收$t1=0.69718900 $t2=1420440552 list($t1, $t2) = explode(' ', microtime()); //转成浮点数 $t1=floatval($t1); $t2=floatval($t2); //相加×1000 $total=( $t1+ $t2) * 1000; //四舍五入 $total=round($total,0); //返回结果 return $total; } echo getMillisecond()," PHP毫秒-getMillisecond()
";
echo getMillisecond_new().' PHP毫秒-getMillisecond_new()'; /* * 思路: * 1.使用microtime()获取微秒时间戳,格式:0.69718900 1420440552 * 2.前后两部分相加×1000,然后四舍五入round($float,0) * 秒time()-->毫秒-->微秒microtime(),两两之间是1000进制 * 这样,就可以与前端JS的时间戳保持一致 * JS : new Date().getTime()获得毫秒时间戳 */ ?> DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> > > -equiv="Content-Type" content="text/html; charset=utf-8"> <span class="pln">time/<span class="pln">title</span></span>> head> >
/
> > var time=new Date(); var mtime=time.getTime(); document.write(mtime+' JS获得毫秒时间戳'); script> body> html> 运行结果如下: 1424069168633 PHP毫秒-getMillisecond() 1424069168633 PHP毫秒-getMillisecond_new() 1424069168643 JS获得毫秒时间戳 可以看出,第三个时间戳数值稍微比前两个大,这是代码运行所消耗的时间,是正常的.
Statement:
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