Format LocalDateTime to String in Java

Java LocalDateTIme to String

In this article, we will see how to format LocalDateTime to String in java.

Java LocalDateTime To String

To format LocalDateTime to String, we can create DateTimeFormatter and pass it to LocalDateTime’s format() method.

Here are steps:

  • Get LocalDateTime instance
  • Create DateTimeFormatter instance with specified format
  • Pass above DateTimeFormatter to format() method to convert LocalDateTime to String in java.

Here is complete code:

Output:

Formatted LocalDateTime in String format : 2022-02-16 18:31

DateTimeFormatter is immutable and thread safe, so you do not have to create new instance every time. It is recommended to declare DateTimeFormatter instance static constant.

Convert LocalDateTime to Time Zone ISO8601 String

In case, you are working with ISO 8601, then you can use LocalDateTime’s atZone() method to get ZoneDateTime object and use toString() method on ZoneDateTime to convert LocalDateTime to String in java.

Parse String to LocalDateTime

Similar to format(), LocalDateTime provides parse() method to convert String to LocalDateTime in Java.
Here is sample code:

That’s all about how to Format LocalDateTime to String in Java 8.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *