Home > Net >  Parse time format yyyy-MM-dd'T'HH:mm:ss.SSS' '
Parse time format yyyy-MM-dd'T'HH:mm:ss.SSS' '

Time:11-16

I am working with jira api and in one of request I get the response with date field in format like this: 2022-10-26T09:34:00.000 0000. I need to convert this to LocalDate but I do not know how to to this with this strange format. Here are some of formats I already tried:

DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS")
DateTimeFormatter.ISO_LOCAL_DATE_TIME

but both cannot deserialize this sign at the end of the date.

Text '2022-10-27T09:34:00.000 0000' could not be parsed, unparsed text found at index 24

CodePudding user response:

You have to add the timezone:

DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ")

Checkout the documentation https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html

CodePudding user response:

The error message is telling you that your DateTimeFormatter is not able to parse the zone offset of 0000 at the end of your String. That's because a DateTimeFormatter.ISO_LOCAL_DATE_TIME just does not expect an offset, it is supposed to only parse

  • year
  • month of year
  • day of month
  • hour of day
  • minute of hour
  • second of minute
  • fraction of second (and nanos)

That's it! No offset! No zone!.

But that also means it could perfectly parse everything until this offset in your example!

However, the String is nearly formatted as an OffsetDateTime, but unfortunately its ISO formatter expects an offset where hours and minutes are separated by a colon, e.g. 00:00, and your String does not have one.

java.time grants you the possibility of building a custom formatter based on an exisiting one. That's why I mentioned above that everything apart from the offset could be parsed with a DateTimeFormatter.ISO_LOCAL_DATE_TIME. You can take that one and attach an offset-x pattern which then parses your unseparated offset. Let's call it extending an existing formatter, here's an example:

public static void main(String[] args) {
    // your example String
    String someTimes = "2022-10-26T09:34:00.000 0000";
    // build a suitable formatter by extending an ISO-formatter
    DateTimeFormatter dtf = new DateTimeFormatterBuilder()
                                    .append(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
                                    .appendPattern("xxxx")
                                    .toFormatter(Locale.ENGLISH);
    // then parse
    LocalDate localDate = LocalDate.parse(someTimes, dtf);
    // and print
    System.out.println(localDate);
}

Output:

2022-10-26

It is always a good idea to create a formatter with a Locale, but in most cases where exclusively numerical values are to be parsed, a formatter without a Locale might be sufficient. That counts for DateTimeFormatter.ofPattern(String, Locale) as well.

  • Related