javadatesimpledateformatdate-formatting

How to convert date in to yyyy-MM-dd Format?


Sat Dec 01 00:00:00 GMT 2012

I have to convert above date into below format

2012-12-01

How can i?

i have tried with following method but its not working

public Date ConvertDate(Date date){

    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    String s = df.format(date);
    String result = s;
    try {
        date=df.parse(result);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return date;
  }

Solution

  • Use this.

    java.util.Date date = new Date("Sat Dec 01 00:00:00 GMT 2012");
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    String format = formatter.format(date);
    System.out.println(format);
    

    you will get the output as

    2012-12-01