Reputation: 824
Currently I am using below date parser to parse the date which is passed as String
:
public static final DateTimeParser FRACTION_PARSER = new DateTimeFormatterBuilder()
.appendLiteral('.').appendFractionOfSecond(0, 3).toParser();
public static final DateTimeFormatter DATE_FORMATTER = new DateTimeFormatterBuilder()
.appendPattern("yyyy-MM-dd'T'HH:mm:ss")
.appendOptional(FRACTION_PARSER).appendLiteral('Z')
.toFormatter();
And I have below conditions to parse:
public static void main(String[] args) {
System.out.println(DATE_FORMATTER.parseDateTime("2016-01-13T13:38:19.679Z"));
System.out.println(DATE_FORMATTER.parseDateTime("2016-01-13T13:38:19.67Z"));
System.out.println(DATE_FORMATTER.parseDateTime("2016-01-13T13:38:19.6Z"));
System.out.println(DATE_FORMATTER.parseDateTime("2016-01-13T13:38:19Z"));
System.out.println(DATE_FORMATTER.parseDateTime("2016-01-15T16:58:57.649-05:00"));
}
It parses the first four cases correctly but is failing for the last one with below error:
Exception in thread "main" java.lang.IllegalArgumentException: Invalid format: "2016-01-15T16:58:57.649-05:00" is malformed at "-05:00"
I understand its failinf as I appended literal Z
to the format. But I was expecting it to work as a timeZone parser!
Is there any simple way to use the same parser with optional parameter for all the above formats? or do I need to use different formats depending on the string that I get?
Upvotes: 0
Views: 212
Reputation: 1741
.appendLiteral('Z')
means that you expect the letter 'Z' here, nothing else.
Use appendTimeZoneOffset(String zeroOffsetText, boolean showSeparators, int minFields, int maxFields)
instead to expect the time zone offset.
For example:
.appendTimeZoneOffset("Z", true, 2, 2)
means time zone offset with hours and minutes or 'Z' for "Zulu" (UTC).
Upvotes: 2