I'm new to java and I'm not understanding what's wrong with my date parsing. I've tried many of the solutions to similar posts, read the DateTimeFormatter documentation and am still stuck. Any help is appreciated. Thank you.
Code
String date = "2021-02-19T00:45:09.798Z"
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSZ");
ZonedDateTime parsedDate = ZonedDateTime.parse(date, formatter);
Error
java.time.format.DateTimeParseException: Text '2021-02-19T00:45:09.798Z' could not be parsed, unparsed text found at index 23
I've also tried using DateTimeFormatter.ofPattern(pattern).withZone(zone)
and receive the same error.
You do not need a formatter to parse the given date-time string as it's already compliant with the default format that ZoneDateTime#parse
expects.
import java.time.ZonedDateTime;
public class Main {
public static void main(String[] args) {
String date = "2021-02-19T00:45:09.798Z";
ZonedDateTime parsedDate = ZonedDateTime.parse(date);
System.out.println(parsedDate);
}
}
Output:
2021-02-19T00:45:09.798Z
Learn more about the modern date-time API from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With