Java examples to format LocalDateTime
instance to String
using DateTimeFormatter
class.
1. Default Format
By default, LocalDateTime format in the following ISO-8601 formats based on the available date and times parts:
uuuu-MM-dd'T'HH:mm
uuuu-MM-dd'T'HH:mm:ss
uuuu-MM-dd'T'HH:mm:ss.SSS
uuuu-MM-dd'T'HH:mm:ss.SSSSSS
uuuu-MM-dd'T'HH:mm:ss.SSSSSSSSS
Let us see an example.
LocalDateTime currentDateTime = LocalDateTime.now();
System.out.println(currentDateTime.toString()); //2022-12-09T18:19:26.492745400
2. LocalDateTime format() API
The format()
method formats the given LocalDateTime instance using the specified format by DateTimeFormatter instance. 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 astatic
constant where possible. We should not need to create new instances everytime we use it.
3. 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 an inbuilt DateTimeFormatter instance using the constant ISO_DATE_TIME.
Finally, use the format() method to get the formatted string.
DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;
String formattedDateTime = currentDateTime.format(formatter);
System.out.println(formattedDateTime); //2022-12-09T18:25:58.6037597
Use ofPattern() method if you want to use a custom pattern for formatting.
DateTimeFormatter customFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");;
String formattedString = currentDateTime.format(customFormat);
System.out.println(formattedString); //2022-12-09 18:25:58
4. Parsing a String to LocalDateTime
The following example 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";
DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;
//Parse String to LocalDateTime
LocalDateTime dateTime = LocalDateTime.parse(dateString, formatter);
Happy Learning !!
Leave a Reply