LocalDate - Java
We have been using java.util.Date for a very long time. There have been times when the basic Date class was not sufficient enough and hence, for my complex project related requirements I often used Joda or Calendar classes etc. for the same. While the inbuilt Date, Calendar etc. classes were provided, I used to write a lot of code for complicated tasks. Using third party libraries was always an option but I am not a very string advocate of using third party libraries until it is absolutely required and save my coding and testing time by a huge margin.
One of the reason when I came across java.time.LocalDate() in JDK8, I was very excited.
Coming to point straightaway, LocalDate object carries information about date, namely year, month, date. It has operations that help us do certain modifications on date.
If we quote java documentation
LocalDate is an immutable date-time object that represents a date, often viewed as year-month-day. Other date fields, such as day-of-year, day-of-week and week-of-year, can also be accessed. For example, the value "2nd October 2007" can be stored in a LocalDate.
It is immutable and thread-safe.
If we want to look at the class definition
public final class LocalDate
implements Temporal, TemporalAdjuster, ChronoLocalDate, Serializable {
Let's start by creating a new LocalDate instance and get current System Time.
The code that does the same is as below
LocalDate localDate = LocalDate.now();
Remember to import java.time.
Output:
Other ways of creating the instance
LocalDate dobSrinivasRamanujan = LocalDate.of(1887, 12, 22);
LocalDate annivDate = LocalDate.parse("2012-07-05");
There are many useful operations, that can be used as well. We would have to agree that a simple operation like getting the day of week was not as simple as the code below.
Adding and Subtracting entities to date can be done as below.
Another useful method.
LocalDate.now().isLeapYear();
Comparing dates is one of the most used operation that I have done in my projects. There are often requirements that needs to check the eligibility or validity based on the dates.
LocalDate.parse("2016-06-12").isBefore(LocalDate.parse("2016-06-11"));
LocalDate.parse("2016-06-12").isAfter(LocalDate.parse("2016-06-11"));
Or using the most used below function
There are many other such methods. For a complete list you can visit the java reference. We can finish up this write up here as this just introduces you to the concept of the LocalDate.
This API however is not limited to just date. We can do a lot more using time as well and we'll try and explore that later
Comments
Post a Comment