Customize parsing and formatting of dates in Java 8

Bertil Muth - Jun 17 '18 - - Dev Community

In Germany, dates have the format dayOfMonth.month.year.
So the day of writing this article is: 17.06.2018

How do you deal with such custom date formats in Java, taking the new DateTime API of Java 8 into account?

Here's a complete listing that first turns a string into a LocalDate, then transforms it back to a string:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class DateTimeParsing {
    public static void main(String[] args) {
        // Parse the date from string, to LocalDate
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");
        LocalDate localDate = LocalDate.parse("17.06.2018", formatter);
        System.out.println("The date is (default formatting): " + localDate);

        // Turn a local date into a string
        String formattedDateString = localDate.format(formatter);
        System.out.println("The date is (formatted): " + formattedDateString);
    }
}
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .