I am using SimpleDateFormat
like this:
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd-HH:mm:ss.SSS");
Date result = sdf.parse("20221114-12:34:56.789");
Works fine for the above example (result: Mon Nov 14 12:34:56 CET 2022
), but works strange for obvious erroneous input:
123-20221114-12:34:56.789
-> Sun Feb 15 12:34:56 CET 728
12320221114-12:34:56.789
-> Mon Nov 21 12:34:56 CET 1289
I would expect to throw ParseException
in these cases.
Note that the timestamp is input and the format cannot be changed.
As a cross-check I tried this: abc-20221114-12:34:56.789
, and at least in this case it threw ParseException
.
The terrible SimpleDateFormat
class was years ago supplanted by the modern java.time classes, specifically DateTimeFormatter
.
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "uuuuMMdd-HH:mm:ss.SSS" );
LocalDateTime result = LocalDateTime.parse( "20221114-12:34:56.789" , f );
The SimpleDateFormat
contains bugs. In the example posted the interpretations are the following:
123-20221114-12:34:56.789
: year 123, month -2, day 221114 12320221114-12:34:56.789
: year 1232, month 02, day 21114 Actually this answers the original question. And as a suggestion the java.time
module should be used introduced in Java 8, as described in other comments.
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.