views:

499

answers:

4

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?

+13  A: 

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
ChssPly76
thanks
Savvas Dalkitsis
+3  A: 

SimpleDateFormat can format and parse a date based on a very simple pattern system that include second and even milliseconds.

Vincent Robert
A: 

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 ...

Erik Tjernlund
That's why everybody should use Joda Time instead, and save themselves headaches :)
Nick
I 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 :-))
Erik Tjernlund
A: 

Also probably off-topic, but for real readability there is an evolving sourceforge project called jFuzzyDate, this project aims to format dates to strings like "yesterday" or "in 5 weeks" which is much more information to most people. The uri is http://jfuzzydate.sourceforge.net/

Bill K