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.

public String format(DateTimeFormatter formatter)

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:

package org.arpit.java2blog;

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

public class LocalDateTimeToStringMain {

    public static void main(String[] args) {
        // Get current LocalDateTime
        LocalDateTime currentLocalDateTime = LocalDateTime.now();

        // Create DateTimeFormatter instance with specified format
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

        // Format LocalDateTime to String
        String formattedDateTime = currentLocalDateTime.format(dateTimeFormatter);

        System.out.println("Formatted LocalDateTime in String format : " + formattedDateTime);
    }
}

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.

LocalDateTime currentDateTime = LocalDateTime.now(); 
ZonedDateTime zdt = currentDateTime.atZone(ZoneOffset.UTC); //you might use a different zone
String iso8601Format = zdt.toString();
// Output : 2022-02-16T18:45:50.408934Z

Parse String to LocalDateTime

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

        // Date in String datatype
        String dateStr = "2022-02-16 18:45";

        // Create DateTimeFormatter instance
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

        // Use Parse method to convert it back to LocalDateTime
        LocalDateTime localDateTime = LocalDateTime.parse(dateStr,dateTimeFormatter);

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

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.