How to correctly create a date with a specific format?

AndreaNobili picture AndreaNobili · May 26, 2015 · Viewed 61.9k times · Source

I have the following doubt related how to create a format date in Java.

In a Java application I have to create a date (the value have to be the current date) formatted in this way: 2015-05-26 (yyyy-mm-dd)

So I know that I can obtain the current date simply build a new java.util.Date object, this way:

Date dataDocumento = new Date();

but how can I specify my date format?

Tnx

Answer

Rahul Tripathi picture Rahul Tripathi · May 26, 2015

Try like this:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date c= sdf.parse("2015-05-26");
String date=sdf.format(c);
System.out.println(date);

To format the current date in yyyy-MM-dd format you can try like this

Date date = new Date();
String str = new SimpleDateFormat("yyyy-MM-dd").format(date);

Kindly refer SimpleDateFormat