Don’t be late for that important date
Specify date formats in Java
October 5, 2001
Q: I would like to retrieve the current date in yyyyMMdd form. What is the easiest way to do that?
A: The easiest way to format a Date
object or a date string is through java.text.DateFormat. The abstract DateFormat
class contains formatting methods as well as static factory methods for retrieving localized DateFormat
objects.
The simplest way to format a date is according to the current locale:
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class DateFormatTest
{
public static void main( String[] args )
{
Calendar calendar = new GregorianCalendar();
Date date = calendar.getTime();
DateFormat localFormat = DateFormat.getDateInstance();
System.out.println( "Localized " + localFormat.format( date ) );
}
}
A call to DateFormat.getDateInstance()
will return a DateFormat
instance that is proper for the runtime’s current locale. On my machine the above code will print out:
Localized Sep 17, 2001
If you choose to defer selection of the formatter to DateFormat
, your dates will always be properly formatted by locale. If you would like to format a date for a specific locale, you can do that too.
In your case, you want to specify the format exactly. You can do so, but be warned that the format might look strange to people in other locales. In order to specify yyyyMMdd or other formats use java.text.SimpleDateFormat. With SimpleDateFormat
, you can specify the format exactly by setting the format in the constructor:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class DateFormatTest {
public static void main( String[] args )
{
Calendar calendar = new GregorianCalendar();
Date date = calendar.getTime();
DateFormat localFormat = DateFormat.getDateInstance();
DateFormat format1 = new SimpleDateFormat( "yyyyMMdd" );
DateFormat format2 = new SimpleDateFormat( "yyyy.MM.dd" );
DateFormat format3 = new SimpleDateFormat( "MM/dd/yyyy" );
DateFormat format4 = new SimpleDateFormat( "MM-dd-yyyy" );
System.out.println( "Localized " + localFormat.format( date ) );
System.out.println( "yyyyMMdd " + format1.format( date ) );
System.out.println( "yyyy.MM.dd " + format2.format( date ) );
System.out.println( "MM/dd/yyyy " + format3.format( date ) );
System.out.println( "MM-dd-yyyy " + format4.format( date ) );
}
}
If you run the above code you will see:
Localized Sep 17, 2001
yyyyMMdd 20010917
yyyy.MM.dd 2001.09.17
MM/dd/yyyy 09/17/2001
MM-dd-yyyy 09-17-2001
For more dates information, see Resources.