Home >Web Front-end >JS Tutorial >How to Convert UTC Epoch to a Local Date in JavaScript?
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.
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);
This approach directly sets the date to the UTC epoch and adjusts it to the desired UTC seconds.
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
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!