Search code examples
javasimpledateformat

Can't make java.text.SimpleDateFormat to work


I have a Date object as follows:

java.util.Date d = new java.util.Date(System.currentTimeMillis()); // Mon Dec 23 14:57:28 PST 2013

I need to format the date to get another Date object with this format instead: 2013-12-23 14:57:28

I tried this code:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
sdf.format(d); // d is still Mon Dec 23 14:57:28 PST 2013, no formatting.

I tried this code:

String s = d.toString();
try {           
        d = sdf.parse(s);
    } catch (Exception e) 
        e.printStackTrace(); // java.text.ParseException: Unparseable date: "Mon Dec 23 14:35:48 PST 2013"

Would you please tell me what am I doing wrong? I googled searched it but the solutions to format a Date was more or less what I tried. Any help is greatly appreciated.


Solution

  • You don't understand what a Date is, and what format() does. A Date is just a number of milliseconds. Nothing more. It doesn't have any format. Formatting a date doesn't change the date at all. It returns a string containing a human readable representation of the date (like "2012-11-23" or "Monday, April 2").

    So, the following instruction:

    sdf.format(d);
    

    is effectively a noop. You ignore the string that it returns.

    If what you want is to have a specific format used when calling date.toString(), it's impossible. When you want to display a date in a specific format (yyyy-MM-dd for example), instead of doing

    System.out.println(date);
    

    use

    DateFormat format = new SimpleDaeFormat("yyyy-MM-dd");
    System.out.println(format.format(date));
    

    All this is clearly explained in the javadoc. You should read it.