Date Time Formatting

suggest change

Before Java 8, the java.text classes DateFormat and SimpleDateFormat were the usual tools, and existing code still uses them. SimpleDateFormat is not thread-safe. DateTimeFormatter is immutable and can be shared.

Java 8 formats and parses through DateTimeFormatter. Build one from a pattern string, then format or parse with it. Letters such as EEE and MMMM follow the formatter's locale, which defaults to the JVM locale.

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

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

        //Parsing
        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

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

        LocalDateTime ldtf1 = LocalDateTime.now();

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

Prefer a predefined formatter to a custom pattern when one fits. The code is clearer, and an ISO-8601 formatter stays unambiguous.

Feedback about page:

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



Table Of Contents