I have been fighting with this for a bit now. I’m trying to convert epoch to a date object. The epoch is sent to me in UTC. Whenever you pass new Date()
an epoch, it assumes it’s local epoch. I tried creating a UTC object, then using setTime()
to adjust it to the proper epoch, but the only method that seems useful is toUTCString()
and strings don’t help me. If I pass that string into a new date, it should notice that it’s UTC, but it doesn’t.
new Date( new Date().toUTCString() ).toLocaleString()
My next attempt was to try to get the difference between local current epoch and UTC current epoch, but I wasn’t able to get that either.
new Date( new Date().toUTCString() ).getTime() - new Date().getTime()
It’s only giving me very small differences, under 1000, which is in milliseconds.
Any suggestions?
Convert from epoch to human-readable dateString date = new java.text.SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(new java.util.Date (epoch*1000)); Epoch in seconds, remove '*1000' for milliseconds.
(GMT-5:00) Eastern Time (US & Canada)Add the local time offset to the UTC time. For example, if your local time offset is -5:00, and if the UTC time is shown as 11:00, add -5 to 11. The time setting when adjusted for offset is 06:00 (6:00 A.M.).
The given epoch days, epoch seconds or epoch milliseconds are converted into LocalDate by adding the given time to 1970-01-01T00:00:00Z.
I think I have a simpler solution -- set the initial date to the epoch and add UTC units. Say you have a UTC epoch var stored in seconds. How about 1234567890
. To convert that to a proper date in the local time zone:
var utcSeconds = 1234567890; var d = new Date(0); // The 0 there is the key, which sets the date to the epoch d.setUTCSeconds(utcSeconds);
d
is now a date (in my time zone) set to Fri Feb 13 2009 18:31:30 GMT-0500 (EST)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With