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