AndreaNobili AndreaNobili - 1 month ago 6
Java Question

How to correctly create a date with a specific format?

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

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