在Laravel中使用Carbon将日期转换为毫秒数

21

我在 Laravel 中使用 Carbon 进行日期处理。

$date = Carbon::createFromDate(2018,02,16);

我该如何将它换算成毫秒?

类似这样:

18:16:30 -> 1532785457060

尝试使用以下代码:strtotime($date) * 1000 - Salman Zafar
这是答案:strtotime($human_readable_date) * 1000。请先尝试搜索,如果没有找到答案,再提出您的问题。您的问题已在此处得到回答:https://dev59.com/GnI_5IYBdhLWcg3wFu_L - MohamedSabil83
可能是重复的问题:https://dev59.com/GnI_5IYBdhLWcg3wFu_L - Oluwatobi Samuel Omisakin
7个回答

12

要获取以毫秒为单位的时间戳,您可以使用

$date = Carbon::now();
$timeInMilliseconds = $date->valueOf()

作为一种替代方案

 $timeInMilliseconds = $date->getPreciseTimestamp(3)

请参考Getters - showdev

11

它能够正常工作,时间为2022年6月。

now()->getTimestampMs()

// 1654259358879

7

这个在 laravel 5.5 版本下和 carbon 1 版本可以正常工作。

$timestamp = (int) round(now()->format('Uu') / pow(10, 6 - 3));

这实际上是 carbon2 中的 getPreciseTimestamp(3) 函数的作用。


1
getPreciseTimestamp 只在 Carbon 2 上可用,而 Laravel 5.5 没有此功能。 - Jose Manuel Marquez

4
您可以转换任何日期。以下是一个示例。
$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。

这个方法对我很有效。


3

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); 


3
>>> $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"

-3

你可以做以下事情

$date = Carbon::createFromDate(2018,02,16); 

// 2018-02-16 15:43:38.617547 Europe/Berlin (+01:00)

$dateInMills = $date->timestamp;

// 1518792294

正如@Keyur Mistry所提到的,时间戳返回的是秒数,而不是毫秒。 - BCsongor
这是秒,不是毫秒! - Azamat

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接