How to Format LocalDateTime in Java

Java examples to format LocalDateTime instance to String using DateTimeFormatter class.

1. Default Format with LocalDateTime.toString()

By default, LocalDateTime format in the following ISO-8601 formats based on the available date and times parts:

uuuu-MM-dd'T'HH:mm
uuuu-MM-dd'T'HH:mm:ss
uuuu-MM-dd'T'HH:mm:ss.SSS
uuuu-MM-dd'T'HH:mm:ss.SSSSSS
uuuu-MM-dd'T'HH:mm:ss.SSSSSSSSS

Let us see an example.

System.out.println( LocalDateTime.now() );   //2022-12-09T18:19:26.492745400

2. LocalDateTime.format() Method

The format() method formats the given LocalDateTime instance using the specified format by DateTimeFormatter instance. It throws DateTimeException – if an error occurs during formatting.

public String format(DateTimeFormatter formatter)

Note that DateTimeFormatter is immutable and thread-safe, and thus the recommended approach is to store it in a static constant where possible. We should not need to create new instances everytime we use it.

3. LocalDateTime Format Examples

3.1. Inbuilt Patterns

In the given example, we have created a new instance using LocalDateTime.now() representing the current date and time. We are using an inbuilt DateTimeFormatter instance using the constant ISO_DATE_TIME. There are several inbuilt patterns available for other frequently used date-time formats.

Finally, use the format() method to get the formatted string.

final static DateTimeFormatter ISO_FORMATTER = DateTimeFormatter.ISO_DATE_TIME;

LocalDateTime ldt = LocalDateTime.now();
String formattedDateTime = ldt.format(ISO_FORMATTER);  //2022-12-09T18:25:58.6037597

3.2. Custom Pattern

Use ofPattern() method if you want to use a custom pattern for formatting.

final static DateTimeFormatter CUSTOM_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

LocalDateTime ldt = LocalDateTime.now();
String formattedString = ldt.format(CUSTOM_FORMATTER);  //2022-12-09 18:25:58

4. Parsing a String to LocalDateTime

The following example parses a given date-time String to LocalDateTime instance. It uses the parse(dateTimeString, formatter) for parsing the given dateTimeString using the provided formatter.

//date in String
String dateString = "2018-07-14T17:45:55.9483536";

DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;

//Parse String to LocalDateTime
LocalDateTime dateTime = LocalDateTime.parse(dateString, formatter);

Happy Learning !!

Sourcecode Download

Comments

Subscribe
Notify of
guest
2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode