不会用以下方法回答这个问题:
Javascript UNIX时间戳以毫秒为单位,PHP时间戳在浏览器中运行,seconds"
”不匹配。
这方面的任何答案都将被否决!
在同一台计算机上,Node.js和PHP在将UTC时间戳字符串转换为UNIX时间戳整数时产生不同的时间戳。
PHP中的参考代码:
$a = '2022-07-20T17:30:28.771';
list($b, $c) = explode('.', $a);
$d = strtotime($b) * 1000 + ((int) $c);
// $d is 1658338228771 ms在Javascript中:
const a = '2022-07-20T17:30:28.771';
const b = new Date(a);
const d = b.valueOf();
// d is 1658352628771 ms见不同之处:
PHP: 1658338228771 milliseconds
Node.js: 1658352628771 milliseconds差正好是14400000毫秒(4小时)。
由于我在EDT时区(UTC-4:00),这可能解释了两者的区别。我的问题是,我该如何调整呢?
在PHP和Javascript中,将UTC时间戳转换为毫秒精度的UNIX时间戳的正确过程是什么?
发布于 2022-07-20 18:29:33
在进一步研究时,我的PHP默认时区被设置为UTC,因此时间戳被解释为UTC。
另一方面,Javascript将其解释为本地时间戳。
要将UTC时间戳可靠地转换为UNIX时间戳,而不管时区设置如何,我需要这样做:
在PHP中:
$a = '2022-07-20T17:30:28.771Z';
$b = new DateTime($a);
$d = (int) $b->format('Uv');
// 1658338228771在Javascript中:
const a = '2022-07-20T17:30:28.771Z';
const b = Date.parse(a);
const d = b.valueOf();
// 1658338228771在这两种情况下,UTC时间戳以Z结尾是很重要的,这样解析器就知道将其视为UTC。
发布于 2022-07-20 18:36:17
$dateTime = new DateTime('2022-07-20T17:30:28.771', new DateTimeZone('UTC'));
$dateTime->add(new DateInterval('PT4H'));
echo $dateTime->format('Uv');打印与您的javascript代码相同。
1658352628771https://stackoverflow.com/questions/73056381
复制相似问题