简体   繁体   中英

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 ?

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).

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM