2

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?

Slava Fomin II
  • 26,865
  • 29
  • 124
  • 202
  • Have you tried this https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date/parse ? – Prabodh M Jun 24 '17 at 08:42
  • The approach would be to first parse the string into JS date and then convert it into LocalDate Object. No additional vanilla library required. – Prabodh M Jun 24 '17 at 09:01

2 Answers2

4

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)
pithu
  • 59
  • 3
1

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());
Prabodh M
  • 2,132
  • 2
  • 17
  • 23
  • It may seem complicated, but it is the cleaner way to do it, maybe not simpler. But manipulating the date string won't be a good idea either. That will be a buggy approach. – Prabodh M Jun 24 '17 at 09:31
  • Well, it makes sense, thank you for clarifying this. I guess I initially was ready to accept the truncation of the time and timezone information. It's acceptable in my specific use case. However, it couldn't be acceptable in general case. – Slava Fomin II Jun 24 '17 at 09:36
  • 1
    You are welcome. It is tricky to deal with dates, I've fallen in many pit falls in past due these devil timezones. If you have date string only, i.e coming from db or somewhere. It would be fine and won't need such manipulation either. The thing is nobody wants to revisit their code to solve datetime bugs. Its hard to debug and solve later than now :) – Prabodh M Jun 24 '17 at 09:41