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?
@Amjad, good idea, but implemented poorly. Try
To convert the current epoch time in [ms] to a 24-hour time. You might need to specify the option to disable 12-hour format.
or as JS:
Note: The use of
en-GB
here, is just a (random) choice of a place using the 24 hour format, it is not your timezone!Considering, you have
epoch_time
available,If you prefer to resolve timestamps and dates conversions from and to UTC and local time without libraries like moment.js, take a look at the option below.
For applications that use UTC timestamps, you may need to show the date in the browser considering the local timezone and daylight savings when applicable. Editing a date that is in a different daylight savings time even though in the same timezone can be tricky.
The
Number
andDate
extensions below allow you to show and get dates in the timezone of the timestamps. For example, lets say you are in Vancouver, if you are editing a date in July or in December, it can mean you are editing a date in PST or PDT.I recommend you to check the Code Snippet down below to test this solution.
Conversions from milliseconds
Conversions from dates
Usage
See it for yourself
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:d
is now a date (in my time zone) set toFri Feb 13 2009 18:31:30 GMT-0500 (EST)
Addition to the above answer by @djechlin
converts EPOCH time to human readable date. Just don't forget that type of EPOCH time must be an Integer.