Friday, June 23, 2017

Java 8- formatted LocalDate & LocalTime using Java.time

Came across a scenario where I need to validate the current date and time in specific format and found this Java.time package which has pretty useful classes for date / time (Ignore if you already know ☺ )

LocalDate


getTodayDate() {
    LocalDate date = LocalDate.now();
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M/d/YYYY");
    System.out.println(date.format(formatter));
}

Output- 6/23/2017 (You can provide different pattern based on your 
requirement like MM/dd/YYYY etc)

The LocalDate class has many useful methods like 
plusMonths, 
plusDays, 
getMonth, 
getDayOfMonth

LocalTime


getTodayTime() {
    LocalTime time = LocalTime.now();
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("h:m a");
    System.out.println(time.format(formatter));
}

Output- 1:20 PM (Based on current time in my system) 
[Here also you can specify different pattern based on your requirement
like "hh:mm a" which will give output as 01:20 PM 
OR 
"HH:mm a" which will give output in 24-hour format like 13:20 PM]

The LocalTime class has many useful plus & get methods 





Java 8- formatted LocalDate & LocalTime using Java.time

Came across a scenario where I need to validate the current date and time in specific format and found this Java.time package which has pret...