Skip to content
Advertisement

Convert Epoch timestamp to ISO in javascript

I have a function in Java to convert an Epoch date to ISO 8601, but I’ve come across the need to do it in Javascript. I have it somewhat working in JS but it needs to be localized to the timezone.

Java version:

JavaScript

Param1: -157737600000

Param2: PST

Output: 1965-01-01T00:00:00-08

My attempt in Javascript:

JavaScript

Essentially I want the same thing that’s coming out of Java, but it’s outputting: 1965-01-01T08:00:00.000Z

By the way, I’m already splitting the date and time up from something that looks like this, so if there is a better to just pass in the following as one string and let Javascript parse it, that would be amazing:

JavaScript

Advertisement

Answer

We can convert the string /Date(-157737600000-0800)/ to a unix time (in ms), and a UTC offset in HHMM using String.match().

The HHMM UTC offset can then be converted to a UTC offset in milliseconds by multiplying the HH value by 3600000 and the MM value by 60000.

We then create a new Date object using the unix time and offset values, since we know the exact offset at that point in time.

We then format using Date.toISOString() and replace the ‘Z’ UTC offset timezone value with the actual UTC offset string (e.g. ‘-08:00’).

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement