Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert date to milliseconds in laravel using Carbon

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
like image 619
Farzaneh Avatar asked Jul 28 '18 13:07

Farzaneh


3 Answers

For get the timestamp in milliseconds you can use

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

As a alternate solution

 $timeInMilliseconds = $date->getPreciseTimestamp(3)
like image 54
Sachintha Avatar answered Oct 23 '22 10:10

Sachintha


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.

like image 37
Ufuk Özcan Avatar answered Oct 23 '22 12:10

Ufuk Özcan


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.

like image 7
Jose Manuel Marquez Avatar answered Oct 23 '22 11:10

Jose Manuel Marquez