Java format LocalDateTime to String

Java example to format LocalDateTime instance to String using DateTimeFormatter class.

1. Format LocalDateTime to String

// Get current date time
LocalDateTime currentDateTime = LocalDateTime.now();

// Inbuilt format
static DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;

// Custom format
//DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

// Format LocalDateTime
String formattedDateTime = currentDateTime.format(formatter);

//Verify
System.out.println("Formatted LocalDateTime : " + formattedDateTime);		

//Output:

//Formatted LocalDateTime : 2018-07-14T17:45:55.9483536
  1. The parse() and format() methods are available for all date/time related objects (LocalDateTime, LocalDate or ZonedDateTime).
  2. DateTimeFormatter is immutable and thread-safe, and thus the recommended approach is to store it in a static constant where possible.

2. Parse String to LocalDateTime

//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);

//Verify
System.out.println("Parsed LocalDateTime : " + dateTime);		

//Output:

//Parsed LocalDateTime : 2018-07-14T17:45:55.948353600

Happy Learning !!

Ref:

DateTimeFormatter JavaDoc
LocalDateTime JavaDoc

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

2 thoughts on “Java format LocalDateTime to String”

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.