Format LocalDateTime to String

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

1. LocalDateTime format()

The format() method formats the given LocalDateTime instance using the specified format. 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.

2. LocalDateTime Format Example

  • In the given example, we have created a new instance using LocalDateTime.now() which represents the current date and time.
  • We are using inbuilt DateTimeFormatter instance using the constant ISO_DATE_TIME. Use ofPattern() method if you want to use a custom pattern for formatting.
  • Finally, use the format() method to get the formatted string.
// Get current date time
LocalDateTime currentDateTime = LocalDateTime.now();

// Inbuilt format
static DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;

// Custom format if needed
//DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

// Format LocalDateTime
String formattedDateTime = currentDateTime.format(formatter);

// Verify
System.out.println("Formatted LocalDateTime : " + formattedDateTime);		
Formatted LocalDateTime : 2018-07-14T17:45:55.9483536

3. Convert String to LocalDateTime

The following example is for reference. It 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";

//Build formatter
static DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;

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

Happy Learning !!

Sourcecode Download

Leave a Reply

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