Home >Web Front-end >JS Tutorial >How to Convert UTC Epoch Timestamps to Local Dates?
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.
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!