Question
What date format is 2011-08-12T20:17:46.384Z?
Answer
The date string "2011-08-12T20:17:46.384Z" follows the ISO 8601 format, which is widely used for representing dates and times in a standardized manner. To parse this format in Java, particularly if you are using an older version like Java 1.4, you will need to utilize the SimpleDateFormat class with a specific format string that captures both the date and time components as well as the timezone information.
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateParser {
public static void main(String[] args) {
String dateStr = "2011-08-12T20:17:46.384Z";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
try {
Date date = format.parse(dateStr);
System.out.println(date);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Causes
- The string uses 'T' as a separator between the date and time components, which is standard in ISO 8601.
- The 'Z' at the end indicates that the time is in UTC (Coordinated Universal Time).
- The presence of milliseconds (.384) requires your format to accommodate this detail.
Solutions
- Use SimpleDateFormat with the pattern "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", where:
- - 'yyyy' represents the year.
- - 'MM' represents the month.
- - 'dd' represents the day of the month.
- - 'T' is a literal character separating date and time.
- - 'HH' represents the hour (0-23).
- - 'mm' represents minutes.
- - 'ss' represents seconds.
- - 'SSS' represents milliseconds.
- - 'Z' is a literal indicating UTC.
Common Mistakes
Mistake: Using DateFormat.getDateInstance() for ISO 8601 formatting.
Solution: Use SimpleDateFormat with the appropriate pattern instead.
Mistake: Not accounting for the 'Z' in the date string.
Solution: Include 'Z' in the format string as a literal.
Mistake: Forget to pattern for milliseconds.
Solution: Make sure to include 'SSS' in the format for milliseconds.
Helpers
- ISO 8601 date format
- Java date parsing
- SimpleDateFormat
- Java date parsing errors
- ParseException in Java
- Java date format strings