Real'sHowTo AddThis Feed Button
Custom Search

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()));
  }
}

blog comments powered by Disqus


If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2014
[ home ]