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

How to Convert UTC Epoch to Local Date?

DDD
Release: 2024-11-19 20:52:02
Original
373 people have browsed it

How to Convert UTC Epoch to Local Date?

Convert UTC Epoch to Local Date: A Comprehensive Solution

The challenge of converting a UTC epoch to a local date arises when the default behavior of the Date() constructor assumes local epoch. This can lead to inaccuracies in date representation.

To address this issue, a more robust approach can be employed:

Solution:

  1. Initialize a Date object to the epoch (0):
var d = new Date(0);
Copy after login
  1. Convert the UTC epoch to seconds:
var utcSeconds = // Replace with your UTC epoch in seconds
Copy after login
  1. Set the UTC seconds using the Date object's setUTCSeconds method:
d.setUTCSeconds(utcSeconds);
Copy after login

This approach ensures that the resulting date, stored in the "d" variable, represents the specified UTC epoch in the local time zone.

Example:

Consider a UTC epoch of 1234567890:

var utcSeconds = 1234567890;
var d = new Date(0);
d.setUTCSeconds(utcSeconds);
Copy after login

The "d" variable will now hold the local date equivalent to this UTC epoch: Fri Feb 13 2009 18:31:30 GMT-0500 (EST).

The above is the detailed content of How to Convert UTC Epoch to Local Date?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template