Parse date

This example will show how to parse a string or text that contains date and time information using java java.text.SimpleDateFormat, java 8 date time API java.time.format.DateTimeFormatter, joda org.joda.time.format.DateTimeFormat and apache commons DateUtils.parseDate.

Straight up Java

@Test
public void parse_date_string_in_java () throws ParseException {

    String superBowlIIAsString = "January 14, 1968";

    SimpleDateFormat formatter = new SimpleDateFormat("MMMM dd, yyyy");
    formatter.setTimeZone(TimeZone.getTimeZone("GMT-0600"));
    Date superBowlIIAsDate = formatter.parse(superBowlIIAsString);

    assertEquals(-62013600000l, superBowlIIAsDate.getTime());
}

Java 8 Date and Time API

Java 8 java.time.format.DateTimeFormatter.ofPattern creates a formatter based on a specified pattern of "MMMM dd, yyyy". In this case, LocalDate.parse will return an instance of LocalDate from the string "January 14, 1968" and the specific formatter.

@Test
public void parse_date_string_in_java8 () {

    java.time.format.DateTimeFormatter formatter =
            java.time.format.DateTimeFormatter.ofPattern("MMMM dd, yyyy");

    String superBowlIIAsString = "January 14, 1968";

    LocalDate superBowlIIAsDate = LocalDate.parse(superBowlIIAsString, formatter);

    assertEquals(1968, superBowlIIAsDate.getYear());
}

Joda Time

Joda DateTimeFormat.forPattern creates a formatter based on a specified pattern of "MMMM dd, yyyy" with a timezone. In this case, "January 14, 1968" will be passed to the DateTimeFormatter.parseDateTime returning a DateTime object.

@Test
public void parse_date_string_in_java_with_joda () {

    String superBowlIIAsString = "January 14, 1968";

    DateTimeFormatter fmt = DateTimeFormat.forPattern("MMMM dd, yyyy")
            .withZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone("GMT-0600")));

    DateTime superBowlIIAsDate = fmt.parseDateTime(superBowlIIAsString);

    assertEquals(-62013600000l, superBowlIIAsDate.getMillis());
}

Apache Commons

Apache commons DateUtils.parseDate will parse "January 14, 1968" which represents a date while passing in the pattern trying to parse.

@Test
public void parse_date_string_in_java_with_apache_commons () throws ParseException {

    String superBowlIIAsString = "January 14, 1968";

    Date superBowlIIAsDate = DateUtils.parseDate(superBowlIIAsString, "MMMM dd, yyyy");

    assertEquals(-62013600000l, superBowlIIAsDate.getTime());
}