user1404982
user1404982

Reputation: 95

Parsing date and time with the new java.time.DateTimeFormatter

I have a date of this type: 2004-12-31 23:00:00-08 but no one of the patterns i know and i have used from the documentation is working. I thought it should something like "yyyy-MM-dd HH:mm:ssX" but it isn't working.

Upvotes: 1

Views: 389

Answers (1)

Meno Hochschild
Meno Hochschild

Reputation: 44061

Sorry for you, but this is a known bug and was already reported in January 2014. According to the bug log a possible solution is deferred.

A simple workaround avoiding alternative external libraries is text preprocessing. That means: Before you parse the text you just append the prefix ":00". Example:

String input = "2004-12-31 23:00:00-08";
String zero = ":00";
if (input.charAt(input.length() - 3) == ':') {
  zero = "";
}
ZonedDateTime zdt = 
  ZonedDateTime.parse(
    input + zero, 
    DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ssXXX"));
System.out.println(zdt);
// output: 2004-12-31T23:00-08:00

UPDATE due to debate with @Seelenvirtuose:

As long as you ONLY have offsets with just hours but without minute part then the pattern "uuuu-MM-dd HH:mm:ssX" will solve your problem, too (as @Seelenvirtuose has correctly stated in his comment).

But if you have to process a list of various strings with mixed offsets like "-08", "Z" or "+05:30" (latter is India standard time) then you should usually apply the pattern containing three XXX. But this currently fails (have verified it by testing in last version of Java-8). So in this case you still have to do text preprocessing and/or text analysis.

Upvotes: 2

Related Questions