简体   繁体   English

将 unix,UTC 时间从 API 端点转换为 React 中的本地时间

[英]Convert unix, UTC time from API endpoint to local time in React

I'm trying to get a weather API setup and wanted to pull in the sunset time.我正在尝试获取天气 API 设置,并想拉入日落时间。 It's in unix,UTC.它位于 unix,UTC。 I've looked up a few discussions but couldn't find something that worked.我查看了一些讨论,但找不到有效的方法。 Here's the API endpoint.这是 API 端点。

"sunset": 1592876160

Here's my code:这是我的代码:

<div>Sunset: {this.state.hits.sunset}</div>

If it's a unix timestamp, you can just multiply by 1000, it converts it to milliseconds, then you can create a Date object making use of that timestamp:如果它是 unix 时间戳,您可以乘以 1000,将其转换为毫秒,然后您可以使用该时间戳创建一个 Date object:

const unixTimestamp = this.state.hits.sunset;
const date = new Date(unixTimestamp * 1e3); // 1e3 === 1000

// Now you can use built-in methods to convert to a local date.
const localized = date.toLocaleDateString();

If you need more customization or want to make more complex operations, moment.js can help.如果您需要更多的自定义或想要进行更复杂的操作, moment.js可以提供帮助。

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

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