mynameisJEFF
mynameisJEFF

Reputation: 4239

Java:failed to parse time string

I was trying to parse the following time string 20180904-23:15:00.000 CST using the following code

DateTimeFormatter abcDateFmt = DateTimeFormatter.ofPattern("yyyyMMdd-HH:mm:ss.SSS [XXX]");

LocalDateTime abcTimestamp = LocalDateTime.parse("20180904-23:15:00.000 CST", abcDateFmt );

Then I came across this exception.

Exception in thread "main" java.time.format.DateTimeParseException: Text '20180904-23:15:00.000 CST' could not be parsed, unparsed text found at index 22
    at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2049)
    at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1948)
    at java.base/java.time.LocalDateTime.parse(LocalDateTime.java:492)

How should I solve this problem ?

Upvotes: 0

Views: 119

Answers (2)

Meno Hochschild
Meno Hochschild

Reputation: 44071

You use the wrong pattern symbol X which symbolizes an offset, not an abbreviation of a zone name. See the javadoc:

   z       time-zone name              zone-name         Pacific Standard Time; PST
   X       zone-offset 'Z' for zero    offset-X          Z; -08; -0830; -08:30; -083015; -08:30:15

Suggestion: Use the pattern letter "z". By the way: "v" as indicated in the other answer of @Ricola represents a generic zone name without any hint if this is standard or daylight time, but your abbreviation "CST" rather indicates the symbol "z" as the right symbol.

I am also wondering why you throw away the zone information after parsing by choosing the type LocalDateTime instead of ZonedDateTime (which you could translate to an instant in next step).

Upvotes: 2

Ricola
Ricola

Reputation: 2932

DateTimeFormatter abcDateFmt = DateTimeFormatter.ofPattern("yyyyMMdd-HH:mm:ss.SSS [v]");
LocalDateTime abcTimestamp = LocalDateTime.parse("20180904-23:15:00.000 CST", abcDateFmt );

From the javadoc:

 X       zone-offset 'Z' for zero    offset-X          Z; -08; -0830; -08:30; 
 v       generic time-zone name      zone-name         Pacific Time; PT
 z       time-zone name              zone-name         Pacific Standard Time; PST

You can either use v or z.

Upvotes: 0

Related Questions