Java Reference
In-Depth Information
4-17. Formatting Dates for Display
Problem
Dates need to be displayed by your application using a specific format. You want to
define that format once and apply it to all dates that need to be displayed.
Solution #1
Utilize the DateTimeFormatter class, part of the new Date-Time API, to format
dates and times according to the pattern you want to use. The DateTimeFormatter
class includes an ofPattern() method, which accepts a string pattern argument to
designate the desired pattern. Each of the temporal date-time classes includes a
format() method, which accepts a DateTimeFormatter and returns the string-
based format of the target date-time object. In the following lines of code, the
DateTimeFormatter is demonstrated:
DateTimeFormatter dateFormatter
= DateTimeFormatter.ofPattern("MMMM dd yyyy");
LocalDateTime now = LocalDateTime.now();
String output = now.format(dateFormatter);
System.out.println(output);
DateTimeFormatter dateFormatter2
= DateTimeFormatter.ofPattern("MM/dd/YY HH:mm:ss");
String output2 = now.format(dateFormatter2);
System.out.println(output2);
DateTimeFormatter dateFormatter3
= DateTimeFormatter.ofPattern("hh 'o''clock' a, zzzz");
ZonedDateTime zdt = ZonedDateTime.now();
String output3 = zdt.format(dateFormatter3);
System.out.println(output3);
Here is the result:
Search WWH ::




Custom Search