Format date

This example will demonstrate how to format a date from a pattern string while using java.text.SimpleDateFormat, String.format, Java 8 date time api, Joda’s DateTimeFormat and apache commons DateFormatUtils.format. DateFormat contains predefined date formats in the JDK which can be used in substitue of a string pattern. January 15, 1967, the date used in the examples below, was the date which the first super bowl was played between Kansas City Chiefs and Green Bay Packers.

Straight up Java

SimpleDateFormat

@Test
public void format_date_in_java () {
    
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.MONTH, Calendar.JANUARY);
    cal.set(Calendar.DAY_OF_MONTH, 15);
    cal.set(Calendar.YEAR, 1967);

    SimpleDateFormat dateFormatter = new SimpleDateFormat("MM/dd/yyyy");
    String dateFirstSuperBowlWasPlayed = dateFormatter.format(cal.getTime());
    
    assertEquals("01/15/1967", dateFirstSuperBowlWasPlayed);
}

String.format

@Test
public void format_date_in_java_using_string_format() {

    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.MONTH, Calendar.JANUARY);
    cal.set(Calendar.DAY_OF_MONTH, 15);
    cal.set(Calendar.YEAR, 1967);
    cal.set(Calendar.HOUR, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.MILLISECOND, 0);

    String str = String.format("Current Date/Time : %tc", cal.getTime());
    
    assertEquals("Current Date/Time : Sun Jan 15 12:00:00 CST 1967", str);
}

Java 8 Date and Time API

The DateTimeFormatter.ofPattern will construct formatter with a MM/dd/YYYY format. Then passing the formatter to LocalDate.format will format this date using the MM/dd/YYYY formatter.

@Test
public void format_date_in_java8 () {
    
    java.time.format.DateTimeFormatter formatter = 
             java.time.format.DateTimeFormatter.ofPattern("MM/dd/yyyy");
     
    LocalDate localDate = LocalDate.of(1967, Month.JANUARY, 15);
    
    String dateFirstSuperBowlWasPlayed = localDate.format(formatter);
    
    assertEquals("01/15/1967", dateFirstSuperBowlWasPlayed);
}

Joda Time

@Test
public void format_date_in_java_with_joda () {
    
    DateTime dateFirstSuperBowlWasPlayed = new DateTime(1967, 1, 15, 0, 0);

    DateTimeFormatter fmt = DateTimeFormat.forPattern("MM/dd/yyyy");
    
    assertEquals("01/15/1967", dateFirstSuperBowlWasPlayed.toString(fmt));
}

Apache Commons

@Test
public void format_date_in_java_with_apachecommons () {

    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.MONTH, Calendar.JANUARY);
    cal.set(Calendar.DAY_OF_MONTH, 15);
    cal.set(Calendar.YEAR, 1967);

    String dateFirstSuperBowlWasPlayed = DateFormatUtils.format(cal, "MM/dd/yyyy");
    assertEquals("01/15/1967", dateFirstSuperBowlWasPlayed);
}