Java 8 new date and time API introduced the
LocalDateTime class that represents both local date and time without timezone information in ISO-8601 format (
yyyy-MM-ddTHH:mm:ss). It is a description of the date, as used for birthdays, combined with the local time as seen on a wall clock.
LocalDateTime is the most popular class from Java 8 new data and time API for handling both date and time together. It provides a broad range of utility methods for different types of date and time operations.
In this quick tutorial, you'll learn how to format an instance of
LocalDateTime to a date-time string in Java 8. Just like LocalDate class,
LocalDateTime also provides
format() method that accepts an instance of
DateTimeFormatter as an argument to format this instance using the specified format:
public String format(DateTimeFormatter formatter)
DateTimeFormatter specifies the pattern that should be used to format the date and it should not be null.
format() returns the formatted date-time string if the specified pattern is valid.
The following example demonstrates how you can get the current LocalDateTime instance and then use
format() method to convert it into a date-time string:
// current date and time LocalDateTime now = LocalDateTime.now(); // format date-time to string String dateStr = now.format(DateTimeFormatter.ofPattern("EEEE, MMMM dd, yyyy hh:mm:ss a")); // print date strings System.out.println("Current Date & Time (before): " + now); System.out.println("Formatted Date & Time (after): " + dateStr);
The above example code will output the following:
Current Date & Time (before): 2019-12-30T17:00:41.375 Formatted Date & Time (after): Monday, December 30, 2019 05:00:41 PM
You can also convert a string to LocalDateTime and then use
format() method to change the date-time string format as shown below:
// old date-time string String oldStr = "12/23/2019 14:55"; // parse old string to date-time LocalDateTime dateTime = LocalDateTime.parse(oldStr, DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm")); // format date-time to string String newStr = dateTime.format(DateTimeFormatter.ofPattern("MMMM dd, yyyy hh:mm a")); // print both strings System.out.println("Date & Time Format (before): " + oldStr); System.out.println("Date & Time Format (after): " + newStr);
Now the output should look like below:
Date & Time Format (before): 12/23/2019 14:55 Date & Time Format (after): December 23, 2019 02:55 PM
Check out How to format a date to string in Java tutorial for more Java 8 new date and time API formatting and parsing examples.
Need help to start a new Spring Boot or MEAN stack project? I am available for contract work. Hire me to accomplish your business goals with engineering and design. Let’s talk about your project: firstname.lastname@example.org.