Home > Web Front-end > JS Tutorial > body text

How to Convert UTC Epochs to Local Date Objects in JavaScript?

Susan Sarandon
Release: 2024-11-13 08:05:02
Original
466 people have browsed it

How to Convert UTC Epochs to Local Date Objects in JavaScript?

Creating Local Date Objects from UTC Epochs

Converting UTC epochs to local date objects can be a challenging task, especially given JavaScript's assumption that epochs are local when passed to its Date constructor. This article addresses this issue, presenting a simple solution that involves setting the date to the epoch and then adding UTC units.

Consider a UTC epoch stored in seconds, such as 1234567890. To convert it to a local date:

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

Now, 'd' represents a date object in your local time zone. For instance, for the given epoch, 'd' would equal:

Fri Feb 13 2009 18:31:30 GMT-0500 (EST)
Copy after login

This solution effectively adjusts the epoch to account for the time difference between UTC and your local time zone. By setting the date to the epoch and then modifying the UTC units, you can accurately convert UTC epochs to local date objects.

The above is the detailed content of How to Convert UTC Epochs to Local Date Objects 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