java.time
In March 2014, Java 8 introduced the modern, java.time date-time API which supplanted the error-prone legacy java.util date-time API. Any new code should use the java.time API. Given below is a solution using modern date-time API:
You do not need a DateTimeFormatter
Your date-time string is in ISO 8601 format, which is also the format that java.time types use by default. So, you do not need to use a DateTimeFormatter explicitly e.g.
Instant instant = Instant.parse("2016-11-18T11:13:43.838Z");
ZonedDateTime zdt = ZonedDateTime.parse("2016-11-18T11:13:43.838Z");
OffsetDateTime odt = OffsetDateTime.parse("2016-11-18T11:13:43.838Z");
Demo:
class Main {
public static void main(String args[]) {
ZonedDateTime zdt = ZonedDateTime.parse("2016-11-18T11:13:43.838Z");
System.out.println(zdt);
// String representation in a custom format
String formatted = zdt.format(
DateTimeFormatter.ofPattern("dd-MMM-uuuu", Locale.ENGLISH));
System.out.println(formatted);
}
}
Output:
2016-11-18T11:13:43.838Z
18-Nov-2016
Online Demo
Some important points:
- If for some reason, you need an instance of
java.util.Date, let java.time API do the heavy lifting of parsing your date-time string and convert zdt from the above code into a java.util.Date instance using Date.from(zdt.toInstant()).
Z denotes zero time zone offset i.e. a time zone offset of +00:00 hours.
What symbol should I use to parse a zone offset string?
You should use X to parse the zone offset in an offset-date-time string that is not in the default format.
| Example of zone offset format |
Pattern |
-08 |
X |
-0830 |
XX |
-08:30 |
XXX |
-08:30:15 |
XXXXX |
So, to parse the time zone offset of Z (or +00:00) in an offset date-time string, which is not in the default format of OffsetDateTime, you should use the symbol X. Check the documentation to learn more about it.
Learn more about the modern Date-Time API from Trail: Date Time
Some useful links:
- Check the answers mentioned in this comment.
- Always specify a
Locale with a date-time formatter for custom formats.
- Check this answer and this answer to learn how to use
java.time API with JDBC.
SimpleDateFormat. Like this:DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");Zis the zero timezone, equivalent to+0000.SimpleDateFormatandDateFormathad tons of problems, andDatewas poorly designed too. Fortunately they are all long outdated.