laravel 使用Carbon在laravel中将日期转换为毫秒
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51572004/
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
Convert date to milliseconds in laravel using Carbon
提问by Farzaneh
i make a date in laravel with carbon
我用碳在laravel中约会
$date = Carbon::createFromDate(2018,02,16);
how should i change it to milliseconds?
我应该如何将其更改为毫秒?
something like this:
像这样:
18:16:30 -> 1532785457060
回答by Al-Mamun Sarkar
Just use timestamp property of Carbon object to get a time in milliseconds.
只需使用 Carbon 对象的时间戳属性来获取以毫秒为单位的时间。
$date->timestamp
Example:
例子:
Carbon\Carbon::now()->timestamp
回答by Takamura
>>> $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"
回答by Sjors Ottjes
Takamura's answer is very close to being correct, but it contains a bug: you have to left pad the number with zeroes or you'll get the wrong answer if the current milliseconds are less than 100.
Takamura 的答案非常接近正确,但它包含一个错误:您必须用零填充数字,否则如果当前毫秒小于 100,您将得到错误的答案。
This example will give you the current time, in milliseconds:
此示例将为您提供当前时间,以毫秒为单位:
$carbon = now();
$nowInMilliseconds = (int) ($now->timestamp . str_pad($now->milli, 3, '0', STR_PAD_LEFT));
To explain why you have to left pad the milliseconds a little bit more:
要解释为什么你必须多留几毫秒:
$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);