Table of Contents
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.
1 2 3 |
public String format(DateTimeFormatter formatter) |
Here are steps:
- Get
LocalDateTime
instance - Create
DateTimeFormatter
instance with specified format - Pass above
DateTimeFormatter
toformat()
method to convert LocalDateTime to String in java.
Here is complete code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
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:
Further reading:
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.
1 2 3 4 5 6 |
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:
1 2 3 4 5 6 7 8 9 10 |
// 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.