How to format a LocaleDateTime in Java8

The java.time.LocalDateTime class can be formatted using the format method and a Formatter.

Syntax:

LocalDateTime ldt = LocalDateTime.now();
String formattedDate3 = ldt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm a"));

Example:

The following example create a LocaDateTime using now. It then formats it in ISO_DATE_TIME, 24H format and 12H format. The output is then written in System out. Not that in 12h format a is added to the format to show if it is AM or PM.

Create the following java file:

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

public class LocalDateTimeTest {

    public static void main(String[] argv) {
	LocalDateTime ldt = LocalDateTime.now();

	String formattedDateIso = ldt.format(DateTimeFormatter.ISO_DATE_TIME);

	String formattedDate2 = ldt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
	String formattedDate3 = ldt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm a"));

	System.out.println("Date in iso format: " + formattedDateIso);
	System.out.println();
	System.out.println("Date in 24H format: " + formattedDate2);
	System.out.println("Date in 12H format: " + formattedDate3);
    }
}


The output will be:

Date in iso format: 2017-10-13T16:48:25.227

Date in 24H format: 2017-10-13 16:48:25
Date in 12H format: 2017-10-13 04:48 PM

References:

Lambda Expressions

Share this article:

Recent Comments