i make a date in laravel with carbon
$date = Carbon::createFromDate(2018,02,16);
how should i change it to milliseconds?
something like this:
18:16:30 -> 1532785457060
i make a date in laravel with carbon
$date = Carbon::createFromDate(2018,02,16);
how should i change it to milliseconds?
something like this:
18:16:30 -> 1532785457060
For get the timestamp in milliseconds you can use
$date = Carbon::now();
$timeInMilliseconds = $date->valueOf()
As a alternate solution
$timeInMilliseconds = $date->getPreciseTimestamp(3)
It works, June, 2022.
now()->getTimestampMs()
// 1654259358879
This works in laravel 5.5
with carbon 1
.
$timestamp = (int) round(now()->format('Uu') / pow(10, 6 - 3));
this is actually what getPreciseTimestamp(3)
in carbon2
does.
You can convert any date. An example is below.
$dateWithMs = '2021-07-30 12:02:07.376000';
$timestamp = (int) round(Carbon::parse($date)->format('Uu') / pow(10, 6 - 3));
You should use Laravel >= 5.5 with Carbon 1.
It is working for me.
>>> $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"
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.
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);
You can do the following
$date = Carbon::createFromDate(2018,02,16);
// 2018-02-16 15:43:38.617547 Europe/Berlin (+01:00)
$dateInMills = $date->timestamp;
// 1518792294
© 2022 - 2024 — McMap. All rights reserved.