How do you convert any ISO8601 string to LocalTime using js-joda?

2.1k views Asked by At

I have a full ISO8601 string, which looks like this: 1989-08-16T00:00:00.000Z. How do I create instance of LocalDate from it using js-joda library?

When trying to parse it directly with LocalDate.parse(), I'm getting the following error:

DateTimeParseException: Text '1989-08-16T00:00:00.000Z' could not be parsed,
unparsed text found at index 10…

I know I can easily split the string at T character or parse it with vanilla Date and then create LocalDate from it, but is there a more simple method, that I can use to easily parse any ISO8601 compatible string to LocalDate?

2

There are 2 answers

3
Prabodh M On BEST ANSWER

First convert your date to Js Date object, then to LocalDate Object.

The Date.parse converts the ISO string to miliseconds and then converting it into JS Date. Eventually using the JS Date object to get LocalDate object.

var jsDate = new Date(Date.parse('1989-08-16T00:00:00.000Z')); //Iso Date string
var LocalDateObj = LocalDate.of(jsDate.getFullYear(), jsDate.getMonth() + 1, jsDate.getDate());
0
pithu On

The ISO string '1989-08-16T00:00:00.000Z' is representing a UTC timestamp.

You can parse this with the corresponding js-joda domain Instant and then convert it to a LocalDate. eg.

let utcTimestamp = Instant.parse('1989-08-16T00:00:00.000Z')
let date = LocalDate.ofInstant(utcTimestamp)