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
Susan SarandonOriginal
2024-11-15 07:00:021053browse

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);

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!

Statement:
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