Share this page 

Simply format a date as "YYYYMMDD"Tag(s): Date and Time


The format "YYYYMMDD" can be useful when sorting records or comparing 2 dates.
public static String getStrDate(GregorianCalendar c) {
 int m = c.get(GregorianCalendar.MONTH) + 1;
 int d = c.get(GregorianCalendar.DATE);
 String mm = Integer.toString(m);
 String dd = Integer.toString(d);
 return "" + c.get(GregorianCalendar.YEAR) + (m < 10 ? "0" + mm : mm) +
     (d < 10 ? "0" + dd : dd);
}
Thanks to Vladimir Garmaev for the bug fix

Or you can use the SimpleDateFormat from the java.text package.

import java.util.Calendar;
import java.text.SimpleDateFormat;

public class TestDate {
  public static void main(String args[]){
    String DATE_FORMAT = "yyyyMMdd";
    SimpleDateFormat sdf =
          new SimpleDateFormat(DATE_FORMAT);
    Calendar c1 = Calendar.getInstance(); // today
    System.out.println("Today is " + sdf.format(c1.getTime()));
  }
}