Java examples to format LocalDateTime
instance to String
using DateTimeFormatter
class.
1. LocalDateTime format()
The format()
method formats the given LocalDateTime instance using the specified format. 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.
2. 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 inbuilt DateTimeFormatter instance using the constant ISO_DATE_TIME. Use ofPattern() method if you want to use a custom pattern for formatting.
- Finally, use the format() method to get the formatted string.
// Get current date time
LocalDateTime currentDateTime = LocalDateTime.now();
// Inbuilt format
static DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;
// Custom format if needed
//DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
// Format LocalDateTime
String formattedDateTime = currentDateTime.format(formatter);
// Verify
System.out.println("Formatted LocalDateTime : " + formattedDateTime);
Formatted LocalDateTime : 2018-07-14T17:45:55.9483536
3. Convert String to LocalDateTime
The following example is for reference. It 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";
//Build formatter
static DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;
//Parse String to LocalDateTime
LocalDateTime dateTime = LocalDateTime.parse(dateString, formatter);
Happy Learning !!
How to arrive at this date format 2019-11-12T06:00:47.588-0600 using date and time formatter
Use this custom pattern : yyyy-MM-dd’T’HH:mm:ss.SSSz