Datetime to Timestamp in milliseconds in PHP

2019-02-25 09:38发布

问题:

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.

回答1:

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, '.', '');


回答2:

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


回答3:

You can use createFromFormat method of DateTime or, better, DateTimeImmutable while passing timezone as third parameter. This way you do not need to rely on default timezone, which is never a good idea

$datetime = DateTimeImmutable::createFromFormat('Y-m-d H:i', '2016-03-22 14:30', new DateTimeZone('Australia/Sydney'));
echo $datetime->getTimestamp();
echo $datetime->format(DateTime::ISO8601);

You can also convert it to another timezone, note that it produced new DateTimeImmutable and original left untouched:

echo $utcTzDatetime = $date->setTimezone(new DateTimeZone('UTC'));
echo $utcTzDatetime->format(DateTime::ISO8601);
echo $datetime->format(DateTime::ISO8601);

Upd:

If format is not fixed, you can let DateTime guess it:

new DateTimeImmutable($time, new DateTimeZone('Australia/Sydney'));

But be aware that if $time string contains timezone or offset, eg '2016-03-22T14:30-0500', it will have priority over timezone parameter and will result in different timestamp!



回答4:

date_default_timezone_set("Australia/Sydney");
echo strtotime('2016-03-22 14:30') * 1000;

Output: 1458617400000



回答5:

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.