Home > Web Front-end > JS Tutorial > How to Convert UTC Epoch Timestamps to Local Dates?

How to Convert UTC Epoch Timestamps to Local Dates?

Susan Sarandon
Release: 2024-11-15 07:00:02
Original
1046 people have browsed it

How to Convert UTC Epoch Timestamps to Local Dates?

Convert UTC Epoch to Local Date

Problem

Converting a UTC epoch timestamp into a local date object can be challenging. The standard Date() constructor interprets epochs as local, leading to incorrect results when the timestamp is actually in UTC. Attempts to create a UTC object and adjust the time using setTime() or retrieve the UTC offset have proven unsuccessful.

Solution

A simpler solution exists to convert UTC epochs to local dates. Instead of manipulating dates directly, set a new date to the epoch (represented as 0) and add the UTC epoch units. For instance, to convert a UTC epoch in seconds (e.g., 1234567890) to a local time:

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

The resulting date, d, will now represent the local time equivalent of the UTC epoch timestamp. In this example, the date would be: Fri Feb 13 2009 18:31:30 GMT-0500 (EST).

The above is the detailed content of How to Convert UTC Epoch Timestamps to Local Dates?. 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