简体   繁体   中英

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

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?

On further investigation, my PHP default timezone was set to UTC, so the timestamp was interpreted as UTC.

Javascript, on the other hand, interprets it as a local timestamp.

To get reliable conversion of a UTC timestamp to a UNIX timestamp regardless of time zone settings, I need to do this:

In PHP:

$a = '2022-07-20T17:30:28.771Z';
$b = new DateTime($a);
$d = (int) $b->format('Uv');
// 1658338228771

In Javascript:

const a = '2022-07-20T17:30:28.771Z';
const b = Date.parse(a);
const d = b.valueOf();
// 1658338228771

In both cases, it is important that the UTC timestamp end with Z , so that the parsers know to treat it as UTC.

  • Create a datetime object with UTC timezone.
  • Add 4 hours
  • Get the timestamp.
$dateTime = new DateTime('2022-07-20T17:30:28.771', new DateTimeZone('UTC'));
$dateTime->add(new DateInterval('PT4H'));
echo $dateTime->format('Uv');

prints the same as your javascript code.

1658352628771

You can use that...

 const UTC_timestamp = YMD_hmsx => // date string conversion to UTC timestamps { let [Y,M,D,h,m,s,x] = YMD_hmsx.split(/\-|T|\:|\.|\Z/).map(Number) return new Date(Date.UTC(Y,--M,D,h,m,s,x)).getTime() } console.log( UTC_timestamp('2022-07-20T17:30:28.771') ) // return -> 1658338228771 , same as PHP
 .as-console-wrapper {max-height: 100% !important;top: 0;} .as-console-row::after {display: none !important;}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM