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

User 1531343 picture User 1531343 · Dec 26, 2012 · Viewed 178.1k times · Source

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;
  }

Answer

Nidhish Krishnan picture Nidhish Krishnan · Dec 26, 2012

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