Format LocalDateTime in Java

Here are some examples to format LocalDateTime in Java:

The following code shows how to format LocalDateTime:


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

public class LocalDateTimeFormattingExample {

	public static void main(String[] args) {

		LocalDateTime now = LocalDateTime.now();
		System.out.println("Before formatting : " + now);
		
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss a");
		String formattedDateTime = now.format(formatter);
		System.out.println("After formatting : " + formattedDateTime);

		}
}

The above code gives the following output:

Before formatting : 2022-01-08T12:21:16.450152400
After formatting : 2022-01-08 12:21:16 PM

Here is another example to format String datetime to LocalDateTime in Java:


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

public class LocalDateTimeFormattingExample {

	public static void main(String[] args) {

		String stringDateTime = "16-01-2022 10:34:45 PM";
		System.out.println("Before formatting : " + stringDateTime);

		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy hh:mm:ss a");
		LocalDateTime formattedLocalDateTime = LocalDateTime.parse(stringDateTime, formatter);
		System.out.println("After formatting : " + formattedLocalDateTime);
		}
}

The above code gives the following output:

Before formatting : 16-01-2022 10:34:45 PM
After formatting : 2022-01-16T22:34:45