简体   繁体   English

使用 JavaScript (React) 将 Unix 日期和时间转换为本地时间

[英]Convert Unix Date and Time to Local Time with JavaScript (React)

I'm trying to convert unix timestamp to local date in a react project.我正在尝试将 unix 时间戳转换为 react 项目中的本地日期。 Below is the function that I'm using:以下是我正在使用的功能:

 function convertDate(unixDate) { const d = new Date(unixDate * 1000); const day = d.toLocaleString(d.getDate()) return(day); }

The date I'm getting is not acurate.我得到的日期不准确。 For example is we run convertDate(1657745369979.82) we should get the date '07/13/2022 8:49:29 PM'.例如,如果我们运行 convertDate(1657745369979.82),我们应该得到日期 '07/13/2022 8:49:29 PM'。 However the date that I'm actually getting is '11/10/54501, 8:59:39 AM'但是我实际得到的日期是 '11/10/54501, 8:59:39 AM'

Why are you multiplying by 1000 ?为什么要乘以 1000 ? This works just fine这工作得很好

new Date(1657745369979.82).toLocaleString() => '14/07/2022, 02:19:29'

which is the same as这与

Convert epoch to human-readable date and vice versa
1657745369979.82
 Timestamp to Human date  [batch convert]
Supports Unix timestamps in seconds, milliseconds, microseconds and nanoseconds.
Assuming that this timestamp is in milliseconds:
GMT: Wednesday, July 13, 2022 8:49:29.979 PM
Your time zone: Thursday, July 14, 2022 2:19:29.979 AM GMT+05:30
Relative: A day ago
 

from https://www.epochconverter.com/来自https://www.epochconverter.com/

If there's more that you want, this old thread should also help Convert a Unix timestamp to time in JavaScript如果你想要更多,这个旧线程也应该有助于将 Unix 时间戳转换为 JavaScript 中的时间

It looks like you do not need to multiply the timestamp by 1000.看起来您不需要将时间戳乘以 1000。

Unix timestamps are often of this length: 1657831769, which would need to be multiplied by 1000 ( https://www.epochconverter.com/ is useful for testing conversions). Unix 时间戳通常是这样的长度:1657831769,这需要乘以 1000( https://www.epochconverter.com/对于测试转换很有用)。

const unixDate = 1657745369979.82;
const d = new Date(unixDate);
console.log(d.toISOString());

Output: 2022-07-13T20:49:29.979Z输出:2022-07-13T20:49:29.979Z

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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