如何在 PHP 中以毫秒为单位获取当前时间?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3656713/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get current time in milliseconds in PHP?
提问by COMer
time()
is in seconds - is there one in milliseconds?
time()
以秒为单位 - 以毫秒为单位吗?
回答by laurent
The short answeris:
在简短的回答是:
$milliseconds = round(microtime(true) * 1000);
回答by kennytm
Use microtime
. This function returns a string separated by a space. The first part is the fractional part of seconds, the second part is the integral part. Pass in true
to get as a number:
使用microtime
. 此函数返回一个由空格分隔的字符串。第一部分是秒的小数部分,第二部分是整数部分。传入true
以获取为数字:
var_dump(microtime()); // string(21) "0.89115400 1283846202"
var_dump(microtime(true)); // float(1283846202.89)
Beware of precision loss if you use microtime(true)
.
如果您使用microtime(true)
.
There is also gettimeofday
that returns the microseconds part as an integer.
还有gettimeofday
将微秒部分作为整数返回。
var_dump(gettimeofday());
/*
array(4) {
["sec"]=>
int(1283846202)
["usec"]=>
int(891199)
["minuteswest"]=>
int(-60)
["dsttime"]=>
int(1)
}
*/
回答by Paolo
Short answer:
简短的回答:
64 bits platforms only!
仅限 64 位平台!
function milliseconds() {
$mt = explode(' ', microtime());
return ((int)$mt[1]) * 1000 + ((int)round($mt[0] * 1000));
}
[ If you are running 64 bits PHP then the constant PHP_INT_SIZE
equals to 8
]
[如果您运行的是 64 位 PHP,则常量PHP_INT_SIZE
等于8
]
Long answer:
长答案:
If you want an equilvalent function of time()
in milliseconds first you have to consider that as time()
returns the number of seconds elapsed since the "epoch time" (01/01/1970), the number of millisecondssince the "epoch time" is a big number and doesn't fit into a 32 bits integer.
如果你首先想要一个time()
以毫秒为单位的等效函数,你必须考虑到time()
返回自“纪元时间”(01/01/1970)以来经过的秒数,自“纪元时间”以来的毫秒数是一个大数字并且不适合 32 位整数。
The size of an integer in PHP can be 32 or 64 bits depending on platform.
PHP 中整数的大小可以是 32 位或 64 位,具体取决于平台。
From http://php.net/manual/en/language.types.integer.php
来自http://php.net/manual/en/language.types.integer.php
The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that's 32 bits signed). 64-bit platforms usually have a maximum value of about 9E18, except for Windows, which is always 32 bit. PHP does not support unsigned integers. Integer size can be determined using the constant PHP_INT_SIZE, and maximum value using the constant PHP_INT_MAX since PHP 4.4.0 and PHP 5.0.5.
整数的大小取决于平台,但通常的值(即 32 位有符号)约为 20 亿的最大值。64 位平台的最大值通常约为 9E18,但 Windows 除外,它始终为 32 位。PHP 不支持无符号整数。自 PHP 4.4.0 和 PHP 5.0.5 起,整数大小可以使用常量 PHP_INT_SIZE 确定,最大值使用常量 PHP_INT_MAX 确定。
If you have 64 bits integers then you may use the following function:
如果您有 64 位整数,那么您可以使用以下函数:
function milliseconds() {
$mt = explode(' ', microtime());
return ((int)$mt[1]) * 1000 + ((int)round($mt[0] * 1000));
}
microtime()
returns the number of seconds since the "epoch time" with precision up to microseconds with two numbers separated by space, like...
microtime()
返回自“纪元时间”以来的秒数,精度高达微秒,两个数字以空格分隔,例如...
0.90441300 1409263371
The second number is the seconds (integer) while the first one is the decimal part.
第二个数字是秒(整数),而第一个数字是小数部分。
The above function milliseconds()
takes the integer part multiplied by 1000
上述函数milliseconds()
取整数部分乘以1000
1409263371000
then adds the decimal part multiplied by 1000
and rounded to 0 decimals
然后添加乘以小数部分1000
并四舍五入到 0 位小数
1409263371904
Note that both $mt[1]
and the result of round
are casted to int
. This is necessary because they are float
s and the operation on them without casting would result in the function returning a float
.
请注意,$mt[1]
和 的结果round
都被强制转换为int
。这是必要的,因为它们是float
s 并且在没有强制转换的情况下对它们的操作将导致函数返回 a float
。
Finally, that function is slightly more precise than
最后,该函数比
round(microtime(true)*1000);
that with a ratio of 1:10 (approx.) returns 1 more millisecond than the correct result.
This is due to the limited precision of the float type (microtime(true)
returns a float).
Anyway if you still prefer the shorter round(microtime(true)*1000);
I would suggest casting to int
the result.
比率为 1:10(大约)的结果比正确结果多返回 1 毫秒。这是由于浮点类型(microtime(true)
返回浮点数)的精度有限。无论如何,如果您仍然喜欢较短的round(microtime(true)*1000);
我建议转换为int
结果。
Even if it's beyond the scope of the question it's worth mentioning that if your platform supports 64 bits integers then you can also get the current time in microsecondswithout incurring in overflow.
即使超出了问题的范围,值得一提的是,如果您的平台支持 64 位整数,那么您也可以获得以微秒为单位的当前时间而不会导致溢出。
If fact 2^63 - 1
(biggest signed integer) divided by 10^6 * 3600 * 24 * 365
(approximately the microseconds in one year) gives 292471
.
如果事实2^63 - 1
(最大的有符号整数)除以10^6 * 3600 * 24 * 365
(大约一年中的微秒)给出292471
.
That's the same value you get with
这与您获得的价值相同
echo (int)( PHP_INT_MAX / ( 1000000 * 3600 * 24 * 365 ) );
In other words, a signed 64 bits integer have room to store a timespan of over 200,000 years measured in microseconds.
换句话说,一个有符号的 64 位整数有空间存储超过 200,000 年的时间跨度(以微秒为单位)。
You may have then
你可能有
function microseconds() {
$mt = explode(' ', microtime());
return ((int)$mt[1]) * 1000000 + ((int)round($mt[0] * 1000000));
}
回答by Andrew Moore
As other have stated, you can use microtime()
to get millisecond precision on timestamps.
正如其他人所说,您可以使用microtime()
以获取时间戳的毫秒精度。
From your comments, you seem to want it as a high-precision UNIX Timestamp. Something like DateTime.Now.Ticks
in the .NET world.
根据您的评论,您似乎希望将其作为高精度 UNIX 时间戳。有点像DateTime.Now.Ticks
.NET 世界。
You may use the following function to do so:
您可以使用以下函数来执行此操作:
function millitime() {
$microtime = microtime();
$comps = explode(' ', $microtime);
// Note: Using a string here to prevent loss of precision
// in case of "overflow" (PHP converts it to a double)
return sprintf('%d%03d', $comps[1], $comps[0] * 1000);
}
回答by Alix Axel
Use microtime(true)
in PHP 5, or the following modification in PHP 4:
microtime(true)
在 PHP 5 中使用,或在 PHP 4 中进行以下修改:
array_sum(explode(' ', microtime()));
A portable way to write that code would be:
编写该代码的可移植方式是:
function getMicrotime()
{
if (version_compare(PHP_VERSION, '5.0.0', '<'))
{
return array_sum(explode(' ', microtime()));
}
return microtime(true);
}
回答by mojmir.novak
echo date('Y-m-d H:i:s.') . gettimeofday()['usec'];
echo date('Y-m-d H:i:s.') . gettimeofday()['usec'];
output:
输出:
2016-11-19 15:12:34.346351
2016-11-19 15:12:34.346351
回答by H? Lê Thi?n Thành
try this:
尝试这个:
public function getTimeToMicroseconds() {
$t = microtime(true);
$micro = sprintf("%06d", ($t - floor($t)) * 1000000);
$d = new DateTime(date('Y-m-d H:i:s.' . $micro, $t));
return $d->format("Y-m-d H:i:s.u");
}
回答by Gras Double
This works even if you are on 32-bit PHP:
即使您使用的是 32 位 PHP,这也有效:
list($msec, $sec) = explode(' ', microtime());
$time_milli = $sec.substr($msec, 2, 3); // '1491536422147'
$time_micro = $sec.substr($msec, 2, 6); // '1491536422147300'
Note this doesn't give you integers, but strings. However this works fine in many cases, for example when building URLs for REST requests.
请注意,这不会给您整数,而是字符串。但是,这在许多情况下都可以正常工作,例如在为 REST 请求构建 URL 时。
If you need integers, 64-bit PHP is mandatory.
如果您需要整数,则必须使用 64 位 PHP。
Then you can reuse the above code and cast to (int):
然后你可以重用上面的代码并转换为(int):
list($msec, $sec) = explode(' ', microtime());
// these parentheses are mandatory otherwise the precedence is wrong!
// ↓ ↓
$time_milli = (int) ($sec.substr($msec, 2, 3)); // 1491536422147
$time_micro = (int) ($sec.substr($msec, 2, 6)); // 1491536422147300
Or you can use the good ol' one-liners:
或者你可以使用好的 ol' one-liners:
$time_milli = (int) round(microtime(true) * 1000); // 1491536422147
$time_micro = (int) round(microtime(true) * 1000000); // 1491536422147300
回答by amnippon
$timeparts = explode(" ",microtime());
$currenttime = bcadd(($timeparts[0]*1000),bcmul($timeparts[1],1000));
echo $currenttime;
NOTE: PHP5 is required for this function due to the improvements with microtime() and the bc math module is also required (as we're dealing with large numbers, you can check if you have the module in phpinfo).
注意:由于 microtime() 的改进,此功能需要 PHP5 并且还需要 bc 数学模块(因为我们正在处理大量数字,您可以检查是否有 phpinfo 中的模块)。
Hope this help you.
希望这对你有帮助。
回答by user3767296
$the_date_time = new DateTime($date_string);
$the_date_time_in_ms = ($the_date_time->format('U') * 1000) +
($the_date_time->format('u') / 1000);