What is DateTimeFormatter in Java?

DateTimeFormatter in Java is a class that provides a way to format and parse dates and times. It is a part of the java.time package introduced in Java 8 and offers both predefined and custom formatting patterns that can be used to display date and time in a human-readable form.

Using DateTimeFormatter, developers can easily convert LocalDate, LocalTime, or LocalDateTime objects to strings in different formats, or convert strings to these date and time objects. This is particularly useful for applications that require date and time manipulation or display in a specific format.

Here is an example of how to use DateTimeFormatter:

import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class DateTimeFormatterExample { public static void main(String[] args) { // Create a DateTimeFormatter DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss"); // Get the current date and time LocalDateTime now = LocalDateTime.now(); // Format the current date and time String formattedDateTime = now.format(formatter); System.out.println("Formatted Date and Time: " + formattedDateTime); } }

DateTimeFormatter Java formatting dates parsing dates LocalDate LocalTime LocalDateTime Java 8