Datetime to Timestamp in milliseconds in PHP
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
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
Pretty self explanatory code, so I wont say much.
date_default_timezone_set('Australia/Sydney'); // set timezone
$yourdate = '2016-03-22 14:30';
$stamp = strtotime($yourdate); // get unix timestamp
$time_in_ms = $stamp*1000;
If you want to display it properly.
echo number_format($time_in_ms, 0, '.', '');