Java8 DateTimeFormatter examples


DateTimeFormatter is a class in Java 8 and later that provides a way to format and parse date-time objects. Here are some examples of how to use DateTimeFormatter:

Format a LocalDateTime object using a predefined format:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class DateTimeFormatterExample {
    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
        String formattedDate = now.format(formatter);
        System.out.println(formattedDate); // output: 2022-05-02T15:30:20.123456
    }
}

Parse a string into a LocalDateTime object using a predefined format:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class DateTimeFormatterExample {
    public static void main(String[] args) {
        String dateString = "2022-05-02T15:30:20.123456";
        DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
        LocalDateTime parsedDate = LocalDateTime.parse(dateString, formatter);
        System.out.println(parsedDate); // output: 2022-05-02T15:30:20.123456
    }
}

Format a LocalDateTime object using a custom format:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class DateTimeFormatterExample {
    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss");
        String formattedDate = now.format(formatter);
        System.out.println(formattedDate); // output: 02/05/2022 15:30:20
    }
}

Parse a string into a LocalDateTime object using a custom format:

javaCopy codeimport java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class DateTimeFormatterExample {
    public static void main(String[] args) {
        String dateString = "02/05/2022 15:30:20";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss");
        LocalDateTime parsedDate = LocalDateTime.parse(dateString, formatter);
        System.out.println(parsedDate); // output: 2022-05-02T15:30:20
    }
}

These are just a few examples of how you can use DateTimeFormatter to format and parse date-time objects in Java. The DateTimeFormatter class provides a wide range of options and configurations for formatting and parsing date-time objects, so be sure to check the Java documentation for more details.