Human readable and parsable date format in Java
Solution 1
Take a look at java.text.SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss.SSS");
Date dt = new Date();
String S = sdf.format(dt); // formats to 09/23/2009 13:53:28.238
Date dt2 = sdf.parse(S); // parses back
Solution 2
SimpleDateFormat
can format and parse a date based on a very simple pattern system that include second and even milliseconds.
Solution 3
Other answers are all good.
But when doing this kind of thing please pick a format that sorts properly when coded as a string.... "yyyy/MM/dd HH:mm:ss" is fine. It always astounds me when software engineers pick a date format which doesn't sort in the obvious, convenient way.
You'll save your fellow developers a lot of pain at some distant point in the future - think of it as good karma :-)
Solution 4
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 theT
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 theirtoString
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.
Solution 5
A little off-topic, but I always feel the need to remind people that DateFormat and SimpleDateFormat are not thread safe! The Sun documentation clearly states this, but I keep finding code out in the wild where people stick a SimpleDateFormat in a static ...
Mohammad Taha
Android geek, TDD nut, International Speaker, ex Shazamer, currently the Principal Software Engineer for Apps at ASOS. Noti.st | Twitter | LinkedIn | GitHub
Updated on July 09, 2022Comments
-
Mohammad Taha almost 2 years
I want to save a Date object to a readable string (for example 22/10/2009 21:13:14) that is also parsable back to a Date object.
I have tried many things and the best I could find was to use DateFormater for parsing and formating but it has a setback. When you format a date you lose seconds information. I tried to find if there is an option to format it and display the seconds (even better would be to the millisecond level since that's the resolution the Date object allows you to have) but I came up short.
Any ideas?
-
Ali Hidim over 14 yearsThat's why everybody should use Joda Time instead, and save themselves headaches :)
-
Erik Tjernlund over 14 yearsI totally agree. On the other hand I want Sun to fix these classes, so if nothing else, I don't have to sit through yet another "concurrency lessons learned"-session with people warning me about them. (Oh the irony ... I just did exactly the same thing here on StackOverflow :-))
-
S.L. Barth over 9 years@Unihedron Updated the link. Reviewers, please note that this is NOT a link-only answer - the answer still has meaning without the link, and the link itself is to the official documentation.
-
UTF_or_Death over 8 years"yyyy/dd/MM" doesn't sort right. Consider that 2015/21/10, 2015/20/11 and 2015/22/11 get sorted into 2015/20/11, 2015/21/10, 2015/22/11 as strings.
-
mikera over 8 yearsSorry I meant yyyy/MM/dd. Fixed.
-
Ole V.V. over 6 yearsWhen this answer was written in 2009,
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. -
Roy Ryando over 4 yearsThe question is to convert Date object, if I want to use your code then I need to convert Date to LocalDateTime, how can I do it?
-
Ole V.V. over 4 yearsThank you, @RoyHabeahan, for your interest. Given an old-fashioned
Date
doString readableString = yourDate.toInstant().toString();
and for the opposite wayDate parsedBack = Date.from(Instant.parse(readableString));
. The string will haveZ
in the end, it denotes UTC. Don't useLocalDateTime
in this case. -
Ole V.V. over 4 yearsOracle (the company that acquired Sun) has fixed it. The classes of java.time, the modern Java date and time API, are thread-safe. Just forget everything about the old
SimpleDateFormat
.