Date Time Formatting

suggest change

Before Java 8, there was DateFormat and SimpleDateFormat classes in the package java.text and this legacy code will be continued to be used for sometime.

But, Java 8 offers a modern approach to handling Formatting and Parsing.

In formatting and parsing first you pass a String object to DateTimeFormatter, and in turn use it for formatting or parsing.

import java.time.*;
import java.time.format.*;

class DateTimeFormat
    public static void main(String[] args) {

        String pattern = "d-MM-yyyy HH:mm";
        DateTimeFormatter dtF1 = DateTimeFormatter.ofPattern(pattern);

        LocalDateTime ldp1 = LocalDateTime.parse("2014-03-25T01:30"), //Default format
                      ldp2 = LocalDateTime.parse("15-05-2016 13:55",dtF1); //Custom format

        System.out.println(ldp1 + "\n" + ldp2); //Will be printed in Default format

        DateTimeFormatter dtF2 = DateTimeFormatter.ofPattern("EEE d, MMMM, yyyy HH:mm");
        DateTimeFormatter dtF3 = DateTimeFormatter.ISO_LOCAL_DATE_TIME;

        LocalDateTime ldtf1 =;

        System.out.println(ldtf1.format(dtF2) +"\n"+ldtf1.format(dtF3));

An important notice, instead of using Custom patterns, it is good practice to use predefined formatters. Your code look more clear and usage of ISO8061 will definitely help you in the long run.

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents