Datetime to Timestamp in milliseconds in PHP
Asked Answered
B

8

15

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.

Bobine answered 21/3, 2016 at 4:54 Comment(1)
Post some code of things you have attempted and why they didn't work. Edit the question, not in the comments.Spectrohelioscope
I
11

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, '.', '');
Involucel answered 21/3, 2016 at 4:59 Comment(4)
You missed - in miliseconds I guess.Pomiculture
Just miltiply by 1000, but it doesnt really make sense why you would want a date converted into milliseconds, unless you're comparing to another date. Because this will just return the amount of milliseconds elapsed since 1970Involucel
@KyleK it's possible he needed it that way to connect to an API that only accepts time stamps with milliseconds, since that's precisely the reason as to why I came to this very answerBodgie
This is not in milliseconds, this is in seconds*1000Topographer
E
23

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
Erminois answered 15/6, 2021 at 1:16 Comment(0)
I
11

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, '.', '');
Involucel answered 21/3, 2016 at 4:59 Comment(4)
You missed - in miliseconds I guess.Pomiculture
Just miltiply by 1000, but it doesnt really make sense why you would want a date converted into milliseconds, unless you're comparing to another date. Because this will just return the amount of milliseconds elapsed since 1970Involucel
@KyleK it's possible he needed it that way to connect to an API that only accepts time stamps with milliseconds, since that's precisely the reason as to why I came to this very answerBodgie
This is not in milliseconds, this is in seconds*1000Topographer
P
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
Populace answered 21/3, 2016 at 5:8 Comment(4)
Hi Rohit, unfortunately,it's not working. I would like to create a time in milliseconds from the input '2016-03-22 14:30' to post it on Onfleet as part of a task. As written on Onfleet Data Types page, the timestamps they use "are consumed and produced in Unix epoch time format, with millisecond precision". when passing the timestamp I receive a message that the timestamp is invalid.Bobine
@Bobine What is the output you are getting?Populace
Have you tried this timestamp 1458671400 . Because Unix epoch time format is same as normal unix timestamp.Populace
Please test it and give me any timestamp example if it wont work.Populace
D
2

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->format('Uv'); // Milliseconds
$timestampUs = (int) $date->format('Uu'); // Microseconds

// Or this gets timestamp in seconds and appends milliseconds
$timestampMs_2 = (int) ($date->getTimestamp() . $date->format('v'));

https://3v4l.org/UoZsL


'v' and 'u' format

Demarcation answered 1/7, 2020 at 9:54 Comment(4)
I was getting confused on why the v format was outputting as text, then in your link I realized it only gets recognized starting at PHP v7. I was able to just do $date->getTimestamp() * 1000 on a PHP v5.4 to get the same value, hopefully no weird gotchas with that.Herve
* 1000 gives you seconds in milliseconds but not actual milliseconds. As you can see, you're loosing precision here: 3v4l.org/bMhAZDemarcation
I didn't know that - how would you recommend those that don't have the option to use $date->format('v')) to get the same precision?Herve
PHP v5.4 was end-of-life at 14 Sep 2015, nobody should use that anymoreErminois
E
1

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!

Efren answered 21/3, 2016 at 9:20 Comment(1)
This is the idiomatic approach in PHPKaycekaycee
G
1

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.

George answered 31/1, 2019 at 6:44 Comment(0)
B
0

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);
?>
Baptistry answered 3/3, 2020 at 13:5 Comment(0)
O
-2
date_default_timezone_set("Australia/Sydney");
echo strtotime('2016-03-22 14:30') * 1000;

Output: 1458617400000

Omnifarious answered 21/3, 2016 at 5:25 Comment(1)
Thanks a lot for your help!Bobine

© 2022 - 2025 — McMap. All rights reserved.