hbrashid
hbrashid

Reputation: 21

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. It's in unix,UTC. I've looked up a few discussions but couldn't find something that worked. Here's the API endpoint.

"sunset": 1592876160

Here's my code:

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

Upvotes: 0

Views: 1275

Answers (1)

Keff
Keff

Reputation: 1071

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:

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.

Upvotes: 1

Related Questions