Human readable and parsable date format in Java

Savvas Dalkitsis picture Savvas Dalkitsis · Sep 23, 2009 · Viewed 19.2k times · Source

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?

Answer

ChssPly76 picture ChssPly76 · Sep 23, 2009

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