John Davidson

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

0 comments
Message:



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?



My Answer:
Using the `Date.parse()` function in JavaScript or the `strtotime()` function in PHP.

Rate this post

5 of 5 based on 9752 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us