How to convert date in to yyyy-MM-dd Format?
UPDATE My Answer here is now outdated. The Joda-Time project is now in maintenance mode, advising migration to the java.time classes. See the modern solution in the Answer by Ole V.V..
Joda-Time
The accepted answer by NidhishKrishnan is correct.
For fun, here is the same kind of code in Joda-Time 2.3.
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;
java.util.Date date = new Date(); // A Date object coming from other code.
// Pass the java.util.Date object to constructor of Joda-Time DateTime object.
DateTimeZone kolkataTimeZone = DateTimeZone.forID( "Asia/Kolkata" );
DateTime dateTimeInKolkata = new DateTime( date, kolkataTimeZone );
DateTimeFormatter formatter = DateTimeFormat.forPattern( "yyyy-MM-dd");
System.out.println( "dateTimeInKolkata formatted for date: " + formatter.print( dateTimeInKolkata ) );
System.out.println( "dateTimeInKolkata formatted for ISO 8601: " + dateTimeInKolkata );
When run…
dateTimeInKolkata formatted for date: 2013-12-17
dateTimeInKolkata formatted for ISO 8601: 2013-12-17T14:56:46.658+05:30
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
String s;
Format formatter;
Date date = new Date();
// 2012-12-01
formatter = new SimpleDateFormat("yyyy-MM-dd");
s = formatter.format(date);
System.out.println(s);
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
.