Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Datetime to Timestamp in milliseconds in PHP

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.

like image 363
Hyacinthe Avatar asked Mar 21 '16 04:03

Hyacinthe


People also ask

How to get datetime With milliseconds in PHP?

parse("01/01/1970 01:00:00"). getTime() / 1000; Timestamp in seconds, remove '/1000' for milliseconds.

How to convert milliseconds to seconds in PHP?

Instead, you will probably just want to do some simple maths: $input = 70135; $uSec = $input % 1000; $input = floor($input / 1000); $seconds = $input % 60; $input = floor($input / 60); $minutes = $input % 60; $input = floor($input / 60); // and so on, for as long as you require.


3 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
like image 99
Michael B. Avatar answered Sep 21 '22 20:09

Michael B.


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

like image 24
simPod Avatar answered Sep 18 '22 20:09

simPod


Try this it will work

<?php
$date = new DateTime('@'.strtotime('2016-03-22 14:30'), new DateTimeZone('Australia/Sydney'));

echo "Timestamp in Australia/Sydney: ".$date->format('Y-m-d H:i:sP');
echo "<br/>";
echo "Timestamp in miliseconds Australia/Sydney: ".strtotime($date->format('Y-m-d H:i:sP'));
?>

Output:

Timestamp in Australia/Sydney: 2016-03-22 18:30:00+00:00
Timestamp in miliseconds Australia/Sydney: 1458671400
like image 27
Rohit Raj Verma Avatar answered Sep 18 '22 20:09

Rohit Raj Verma