Home:ALL Converter>Converting UTC timestamp string to UNIX timestamp number - Javascript vs PHP

Converting UTC timestamp string to UNIX timestamp number - Javascript vs PHP

Ask Time:2022-07-21T02:12:02         Author:Jonathon Hill

Json Formatter

Do NOT answer this question with the following:

  • "Javascript UNIX timestamps are in milliseconds, PHP UNIX timestamps are in seconds"
  • "Javascript runs in the browser, PHP runs on the server, and the clocks might not match"

Any answers to that effect will be downvoted!

I'm running into an issue where on the exact same computer, Node.js and PHP yield different timestamps when converting a UTC timestamp string to an UNIX timestamp integer.

Reference code in PHP:

$a = '2022-07-20T17:30:28.771';
list($b, $c) = explode('.', $a);
$d = strtotime($b) * 1000 + ((int) $c);
// $d is 1658338228771 ms

In Javascript:

const a = '2022-07-20T17:30:28.771';
const b = new Date(a);
const d = b.valueOf();
// d is 1658352628771 ms

See the difference:

PHP:     1658338228771 milliseconds
Node.js: 1658352628771 milliseconds

The difference is exactly 14400000 milliseconds (4 hours).

Since I am in the EDT timezone (UTC-4:00), that probably explains the difference. My question is, how do I adjust for this?

What is the proper procedure for converting a UTC timestamp to a UNIX timestamp with millisecond precision that matches in both PHP and Javascript?

Author:Jonathon Hill,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/73056381/converting-utc-timestamp-string-to-unix-timestamp-number-javascript-vs-php
Jonathon Hill :

On further investigation, my PHP default timezone was set to UTC, so the timestamp was interpreted as UTC.\nJavascript, on the other hand, interprets it as a local timestamp.\nTo get reliable conversion of a UTC timestamp to a UNIX timestamp regardless of time zone settings, I need to do this:\nIn PHP:\n$a = '2022-07-20T17:30:28.771Z';\n$b = new DateTime($a);\n$d = (int) $b->format('Uv');\n// 1658338228771\n\nIn Javascript:\nconst a = '2022-07-20T17:30:28.771Z';\nconst b = Date.parse(a);\nconst d = b.valueOf();\n// 1658338228771\n\nIn both cases, it is important that the UTC timestamp end with Z, so that the parsers know to treat it as UTC.",
2022-07-20T18:29:33
yy