-->
Skip to main content

LocalDateTime to String Conversion In Java [2021]

LocalDateTime to String Conversion In Java [2021] 

In this tutorial, we will see how we can convert LocalDateTime to String In Java. In the earlier tutorial, we have seen LocalDateTime to date Conversion In Java 

LocalDateTime to String

LocalDateTime to String Conversion

There is LocalDateTime.format(DateTimeFormatter formatter) method to build LocalDateTime to string in java. Here is the method description :

public String format(DateTimeFormatter formatter)

This method formats date-time passed using the specified formatted. This date-time object will be passed to the formatter to produce a string.

Specified by:

format method is declared in interface ChronoLocalDateTime<LocalDate>.

Parameters:

formatter - the formatter to use which is not null.

Returns:

the formatted date-time string which is not null.

Throws:

DateTimeException is thrown if an error occurs during printing.

Example:

 import java.time.LocalDateTime;
 import java.time.format.DateTimeFormatter;
 
 public class LocalDateTimeToStringExample {
    public static void main(String[] args) {
	// Creating LocalDateTime instance
	LocalDateTime now = LocalDateTime.now();
		
	// Printing now instance
	System.out.println("Current DateTime Object : " + now);

	// Creating formatter using predefined library constants
	DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;

	// Creating Custom formatter
 	DateTimeFormatter customFormatter = DateTimeFormatter.ofPattern("dd-MMM-yyyy HH:mm:ss");

	// Converting LocalDateTime instance to String format using predefined formatter.
	String formattedDateTime1 = now.format(formatter);

	// Converting LocalDateTime instance to String format using predefined formatter.
	String formattedDateTime2 = now.format(customFormatter);

	// Printing LocalDateTime in String format using predefined formatter
	System.out.println("Current DateTime in String Form Predefined Formatter : " + formattedDateTime1);

	// Printing LocalDateTime in String format using Custom formatter
	System.out.println("Current DateTime in String Form Custom Formatter : " + formattedDateTime2);

    }
 }

Output:

Current DateTime Object : 2020-07-02T19:47:48.036
Current DateTime in String Form Predefined Formatter : 2020-07-02T19:47:48.036
Current DateTime in String Form Custom Formatter : 02-Jul-2020 19:47:48

Conclusion:

In this tutorial, we have covered how we can convert LocalDateTime to String in Java using the LocalDateTime.format(DateTimeFormatter formatter) method.

Happy Learning!!!

Comments