我在 Laravel 中使用 Carbon 进行日期处理。
$date = Carbon::createFromDate(2018,02,16);
我该如何将它换算成毫秒?
类似这样:
18:16:30 -> 1532785457060
我在 Laravel 中使用 Carbon 进行日期处理。
$date = Carbon::createFromDate(2018,02,16);
我该如何将它换算成毫秒?
类似这样:
18:16:30 -> 1532785457060
要获取以毫秒为单位的时间戳,您可以使用
$date = Carbon::now();
$timeInMilliseconds = $date->valueOf()
作为一种替代方案
$timeInMilliseconds = $date->getPreciseTimestamp(3)
它能够正常工作,时间为2022年6月。
now()->getTimestampMs()
// 1654259358879
这个在 laravel 5.5
版本下和 carbon 1
版本可以正常工作。
$timestamp = (int) round(now()->format('Uu') / pow(10, 6 - 3));
这实际上是 carbon2
中的 getPreciseTimestamp(3)
函数的作用。
$dateWithMs = '2021-07-30 12:02:07.376000';
$timestamp = (int) round(Carbon::parse($date)->format('Uu') / pow(10, 6 - 3));
建议使用 Laravel >= 5.5 版本,搭配 Carbon 1。
这个方法对我很有效。
Takamura的回答非常接近正确,但它包含一个错误:您必须使用零左填充数字,否则如果当前毫秒数小于100,则会得到错误的答案。
此示例将为您提供当前时间(以毫秒为单位):
$carbon = now();
$nowInMilliseconds = (int) ($now->timestamp . str_pad($now->milli, 3, '0', STR_PAD_LEFT));
$seconds = 5;
$milliseconds = 75; // milliseconds are always between 0 and 999
// wrong answer: 575
$totalInMs = $seconds . $milliseconds;
// correct answer: 5075
$totalInMs = $now->timestamp . str_pad($now->milli, 3, '0', STR_PAD_LEFT);
>>> $now = now();
=> Illuminate\Support\Carbon @1571283623 {#2987
date: 2019-10-17 03:40:23.530274 UTC (+00:00),
}
>>> $now->timestamp
=> 1571283623
>>> $x = $now->timestamp . $now->milli
=> "1571283623530"
>>> \Carbon\Carbon::createFromTimestampMs($x)->toDateTimeString()
=> "2019-10-17 03:40:23"
>>> >>> \Carbon\Carbon::createFromTimestampMs($x)->format('Y-m-d H:i:s.u')
=> "2019-10-17 03:40:23.530000"
你可以做以下事情
$date = Carbon::createFromDate(2018,02,16);
// 2018-02-16 15:43:38.617547 Europe/Berlin (+01:00)
$dateInMills = $date->timestamp;
// 1518792294