ISO 8601
Use ISO 8601 format.
- It’s flexible, it includes seconds and fraction of second if there are any, but you may also leave them out if they are 0.
- It’s standard, so more and more tools format and parse it. Great for serialization for storage or data interchange.
- It goes like
2009-10-22T21:13:14
, I should say it’s pretty human-readable (though the T
in the middle that denotes the start of the time part may feel unusual at first).
- The strings sort properly, as mikera requested in another answer, as long as the years are in the four-digit range from 1000 through 9999.
- The classes of
java.time
, the modern Java date and time API, as well as those of Joda Time parse ISO 8601 as their default, that is, without any explicit formatter, and produce the same format from their toString
methods.
A modest demonstration of using java.time
:
LocalDateTime dateTime = LocalDateTime.of(2009, 10, 22, 21, 13, 14);
String readableString = dateTime.toString();
System.out.println(readableString);
LocalDateTime parsedBack = LocalDateTime.parse(readableString);
System.out.println(parsedBack);
This prints two identical lines:
2009-10-22T21:13:14
2009-10-22T21:13:14
The latter System.out.println()
call implicitly calls toString()
once more, so this shouldn’t surprise.
SimpleDateFormat
was what we had for this purpose. It has proven troublesome and has fortunately been replaced byjava.time
, the modern Java date and time API, and itsDateTimeFormatter
class in 2014. I recommend you never useSimpleDateFormat
again. – Rutilant