Modern answer: Use LocalDate
from java.time
, the modern Java date and time API, and its toString
method:
LocalDate date = LocalDate.of(2012, Month.DECEMBER, 1); // get from somewhere
String formattedDate = date.toString();
System.out.println(formattedDate);
This prints
2012-12-01
A date (whether we’re talking java.util.Date
or java.time.LocalDate
) doesn’t have a format in it. All it’s got is a toString
method that produces some format, and you cannot change the toString
method. Fortunately, LocalDate.toString
produces exactly the format you asked for.
The Date
class is long outdated, and the SimpleDateFormat
class that you tried to use, is notoriously troublesome. I recommend you forget about those classes and use java.time
instead. The modern API is so much nicer to work with.
Except: it happens that you get a Date
from a legacy API that you cannot change or don’t want to change just now. The best thing you can do with it is convert it to java.time.Instant
and do any further operations from there:
Date oldfashoinedDate = // get from somewhere
LocalDate date = oldfashoinedDate.toInstant()
.atZone(ZoneId.of("Asia/Beirut"))
.toLocalDate();
Please substitute your desired time zone if it didn’t happen to be Asia/Beirut. Then proceed as above.
Link: Oracle tutorial: Date Time, explaining how to use java.time
.