Oracle Certified Associate: Java 8 Formatting Date and Time

In previous post we learned how to manipulate date and time object. In this post we will see how to parse and format the date and time. 

For formatting date and time in Java 8 DateTimeFormatter is used which belongs to java.time.format package. It is used to parse the string in to date and time and also used to print the date time in desired format, all date time related class provides two methods for the same viz parse and format.
Formatting the Date 

DateTimeFormatter have some standard or predefined format that can be used for example

LocalDate date = LocalDate.of(2016, Month.APRIL, 20);
LocalTime time = LocalTime.of(10, 10, 30);
LocalDateTime dateTime = LocalDateTime.of(date, time);

Defining Custom Format

DateTimeFormatter f = DateTimeFormatter.ofPattern("dd/MMM/yyyy");
System.out.println(date.format(f)); // 20/Apr/2015

Parsing String to Date
String x = "20 Apr 2016"
DateTimeFormatter f = DateTimeFormatter.ofPattern("dd MMM yyyy");
LocalDate test = LocalDate.parse(x, f);

Thats it for the new date time in Java 8. For more detail refer to java docs.

Labels: , , ,