LocalDateTime to String in Java [2 ways]

In this post, I will share how to convert LocalDateTime to String in Java. There are two ways to achieve our goal of converting LocalDateTime to String in Java:

1. Using LocalDateTime class format() method [Recommended]

2. Using LocalDateTime class atZone() method

Read Also: LocalDateTime to Instant in Java

Convert LocalDateTime to String in Java

1. Using the LocalDateTime class format() method

We can easily convert LocalDateTime to String in Java using the LocalDateTime.format() method passing DateTimeFormatter as the input argument as shown below in the example:

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

public class LocalDateTimeToString {
  public static void main(String args[]) {
    // Create LocalDateTime object
    LocalDateTime localDateTime = LocalDateTime.now();
    System.out.println("The current LocalDateTime is: " + localDateTime);
    
    // Create DateTimeFormatter object with specified format
    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
    
    // Convert LocalDateTime to String
    String str = localDateTime.format(dateTimeFormatter);
    
    System.out.println("Converted LocalDateTime to String: " + str);
    
  }
}


Output:
The current LocalDateTime is: 2024-10-06T11:42:53.227102264
Converted LocalDateTime to String: 2024-10-06 11:42


2. Using LocalDateTime class atZone() method

We can easily convert LocalDateTime to String in Java using LocalDateTime.atZone() and ZonedDateTime.toString() methods passing ZoneOffset as input argument as shown below in the example:

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;

public class LocalDateTimeToString2 {
  public static void main(String args[]) {
    // Create LocalDateTime instance
    LocalDateTime localDateTime = LocalDateTime.now();
    System.out.println("Current LocalDateTime is: " + localDateTime);
    
    // Create ZonedDateTime object 
    ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneOffset.UTC);
    
    // Converting ZonedDateTime to String
    String str = zonedDateTime.toString();
    
    System.out.println("Converted LocalDateTime to String using ZonedDateTime: " + str);
    
  }
}


Output:
Current LocalDateTime is: 2024-10-06T18:11:55.548865427
Converted LocalDateTime to String using ZonedDateTime: 2024-10-06T18:11:55.548865427Z


That's all for today. Please mention in the comments if you have any questions related to how to convert LocalDateTime to String in Java with examples.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry