Datetime to Timestamp in milliseconds in PHP

Viewed 35681

I would like to create a timestamp in milliseconds from the input '2016-03-22 14:30'. Also the timezone specified should be Australia/Sydney.

I've tried different approaches but none seem to be working.

Can anyone help me please? I'm really struggling with that.

8 Answers

Answers with * 1000 are only formatting the output, but don't capture the precision.

With DateTime->format, where U is for seconds, u for microsecond and v for millisecond:

<?php
// pass down `now` or a saved timestamp like `2021-06-15 01:03:35.678652`
$now = new \DateTime('now', new \DateTimeZone('UTC'));
// or something like:
$now = DateTime::createFromFormat('U.u', number_format(microtime(true), 6, '.', ''), new \DateTimeZone('UTC'));

// in microseconds:
$now_us = (int)$now->format('Uu');
// e.g.: 1623719015678652


// in milliseconds:
$now_ms = (int)$now->format('Uv');
// e.g.: 1623719015678

If you are using Carbon package then you can use

Carbon::parse('2009-09-22 16:47:08.128')->micro

This will return you time in microseconds. You can divide that by 1000 and concatenate that with the epoch timestamp of same date in seconds.
Just make sure that if the date format has no millisecond component then you will get 0 as microseconds and you will have to pad that 0 with extra zeroes before concatenation.

For those looking how to get timestamp in milliseconds from DateTime, this is what I've come up with:

$date = new DateTimeImmutable();

$timestampMs = (int) ($date->getTimestamp() . $date->format('v'));

This gets timestamp in seconds and appends milliseconds ('v' format).

https://3v4l.org/UoZsL

Try this method simply

<?php
$time = microtime(true);
$datetime = new DateTime();
$datetime->setTimestamp($time);
$format = $datetime->format('Y-m-d H:i:s');
var_dump($format);
?>
Related