Working with Time and Date in Java
Working with time and date in Java is essential to any project.
There are three important classes you can use:
- java.time.LocalTime - working only with time.
- java.time.LocalDate - working only with date.
- java.time.LocalDateTime - working with time and date both.
All three classes provide two essential methods:
- of(arguments) - accepting arguments for the time/date/datetime values.
- now() - creating an object for the current time/date/datetime values.
Here are a few examples. Creating objects with now:
LocalTime now = LocalTime.now();
LocalDate today = LocalDate.now();
LocalDateTime ldt = LocalDateTime.now();
The above would print respectively:
11:37:16.733
2017-10-28
2017-10-28T11:37:16.733
Similarly, you can parse the above values to create an object with the of() method like this:
LocalTime now = LocalTime.of(11,37,16);
LocalDate today = LocalDate.of(2017,10,28);
LocalDateTime ldt = LocalDateTime.of(2017,10,28,11,37);
This is good to know not only about your daily programming tasks but also about exams such as Oracle 1z0-808.
Liked it? Check also our other article How to parse time in Java.