I am trying to parse a timestamp with a SimpleDateFormat but it raises ParseException in Java 1.8. The same code works flawlessly in Java 9 or higher. The example code snippet
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.text.SimpleDateFormat;
import java.text.ParseException;
public class TestStrftime{
public static void main(String []args) throws ParseException {
String TS_FMT = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
SimpleDateFormat dateFormat = new SimpleDateFormat(TS_FMT);
String szSableTimeStamp = "2020-01-16T19:32:13.540000Z";
Instant sableTimestamp = dateFormat
.parse(szSableTimeStamp)
.toInstant().truncatedTo(ChronoUnit.SECONDS);
System.out.println(sableTimestamp);
}
}
and it raises the exception
Exception in thread "main" java.text.ParseException: Unparseable date: "2020-01-16T19:32:13.540000Z"
at java.text.DateFormat.parse(DateFormat.java:366)
at TestStrftime.main(TestStrftime.java:12)
but with Java 9 or higher, its able to parse the date with the desired output
2020-01-16T19:41:13Z
DateTimeFormatter?2020-01-16T19:41:13Zbe the desired output from parsing2020-01-16T19:32:13.540000Z?? It’s 8 and a half minutes off.szSableTimeStampseems to be wrong. Some C++ guidelines say to useszat prefix for zero terminated strings. But Java strings are not zero terminated.SimpleDateFormat. That class is notoriously troublesome and long outdated. Instead useDateTimeFormatterfrom java.time, the modern Java date and time API. (where alsoInstantandChronoUnitcome from)