How to convert date in to yyyy-MM-dd Format?
Sebastian Wright
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; } 7 6 Answers
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 2 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); 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 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.
You can't format the Date itself. You can only get the formatted result in String. Use SimpleDateFormat as mentioned by others.
Moreover, most of the getter methods in Date are deprecated.
A date-time object is supposed to store the information about the date, time, timezone etc., not about the formatting. You can format a date-time object into a String with the pattern of your choice using date-time formatting API.
- The date-time formatting API for the modern date-time types is in the package,
java.time.formate.g.java.time.format.DateTimeFormatter,java.time.format.DateTimeFormatterBuilderetc. - The date-time formatting API for the legacy date-time types is in the package,
java.texte.g.java.text.SimpleDateFormat,java.text.DateFormatetc.
Demo using modern API:
import java.time.LocalDate;
import java.time.Month;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main { public static void main(String[] args) { ZonedDateTime zdt = ZonedDateTime.of(LocalDate.of(2012, Month.DECEMBER, 1).atStartOfDay(), ZoneId.of("Europe/London")); // Default format returned by Date#toString System.out.println(zdt); // Custom format DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH); String formattedDate = dtf.format(zdt); System.out.println(formattedDate); }
}Output:
2012-12-01T00:00Z[Europe/London]
2012-12-01Learn about the modern date-time API from Trail: Date Time.
Demo using legacy API:
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
public class Main { public static void main(String[] args) { Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT")); calendar.setTimeInMillis(0); calendar.set(Calendar.YEAR, 2012); calendar.set(Calendar.MONTH, 11); calendar.set(Calendar.DAY_OF_MONTH, 1); Date date = calendar.getTime(); // Default format returned by Date#toString System.out.println(date); // Custom format SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH); String formattedDate = sdf.format(date); System.out.println(formattedDate); }
}Output:
Sat Dec 01 00:00:00 GMT 2012
2012-12-01Some more important points:
- The
java.util.Dateobject is not a real date-time object like the modern date-time types; rather, it represents the milliseconds from theEpoch of January 1, 1970. When you print an object ofjava.util.Date, itstoStringmethod returns the date-time calculated from this milliseconds value. Sincejava.util.Datedoes not have timezone information, it applies the timezone of your JVM and displays the same. If you need to print the date-time in a different timezone, you will need to set the timezone toSimpleDateFomratand obtain the formatted string from it. - The date-time API of
java.utiland their formatting API,SimpleDateFormatare outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API.- For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7.
- If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.