Home > Web Front-end > JS Tutorial > How to Convert UTC Epoch to a Local Date in JavaScript?

How to Convert UTC Epoch to a Local Date in JavaScript?

Barbara Streisand
Release: 2024-11-16 00:03:02
Original
819 people have browsed it

How to Convert UTC Epoch to a Local Date in JavaScript?

Converting UTC Epoch to Local Date

Converting UTC epoch to a local date object can be a tricky task. By default, JavaScript's new Date() assumes the epoch time is local, leading to confusion when dealing with UTC epochs.

Solutions

Solution 1: Using setUTCSeconds() Method

Instead of adjusting a UTC object using setTime(), which doesn't always yield accurate results, consider setting the initial date to the epoch and adding UTC units.

var utcSeconds = 1234567890;
var d = new Date(0); // Sets the date to the epoch
d.setUTCSeconds(utcSeconds);
Copy after login

This approach directly sets the date to the UTC epoch and adjusts it to the desired UTC seconds.

Alternate Solution: Calculating Time Difference

If the above solution doesn't work, you can try calculating the time difference between the local current epoch and the UTC current epoch. Here's a modified version of the code you provided:

var utcSeconds = 1234567890;
var utcDate = new Date(utcSeconds * 1000); // Convert seconds to milliseconds
var localDate = new Date();
var timeDifference = localDate.getTime() - utcDate.getTime();

console.log(timeDifference);  // This should give you the time difference in milliseconds
Copy after login

Ensure to convert the UTC seconds to milliseconds before creating the utcDate object. The timeDifference will then provide the milliseconds difference between the local time and UTC time, allowing for accurate adjustments.

The above is the detailed content of How to Convert UTC Epoch to a Local Date in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template