JavaEssential standard classesDate and time

LocalDate

The class LocalDate represents a single date without a time, such as 2017-11-25 or 2025-01-23 (year, month, day). It could be used to store a birthday or another day of the apocalypse.

The class belongs to the java.time package.

An instance storing the current date can be created as below:

LocalDate now = LocalDate.now();

Of course, it's possible to create an instance of LocalDate that represents a specific day of a year. It can be obtained using two special static methods: of and parse.

Here are two example below.

LocalDate date1 = LocalDate.of(2017, 11, 25); // 2017-11-25 (25 November 2017)
LocalDate date2 = LocalDate.parse("2017-11-25"); // 2017-11-25 (25 November 2017)

The number of a month is a number from 1 to 12 inclusive, the first day in a month has the number 1.

It's possible to create an instance of LocalDate with a year and the number of a day in this year:

LocalDate.ofYearDay(2017, 33); // 2017-02-02 (2 February 2017)

A number of a day in the year is an int number from 0 to 365-366 (depending on whether a leap year or not).

LocalDate.ofYearDay(2016, 365); // 2016-12-30 (30 December 2016)
LocalDate.ofYearDay(2017, 365); // 2017-12-31 (31 December 2017)

LocalDate.ofYearDay(2016, 366); // 2016-12-31 (31 December 2016)
LocalDate.ofYearDay(2017, 366); // here is an exception occurs, because the year is not leap

If we have an instance LocalDate we can get the year, month, the day of a month, the day of a year:

LocalDate date = LocalDate.of(2017, 11, 25); // 2017-11-25 (25 November 2017)

int year = date.getYear(); // 2017
int month = date.getMonthValue(); // 11
int dayOfMonth = date.getDayOfMonth(); // 25
int dayOfYear = date.getDayOfYear();  // 329

Also, we can get a length of the year and month:

LocalDate date = LocalDate.of(2017, 11, 25); // 2017-11-25 (25 November 2017)

int lenOfYear = date.lengthOfYear(); // 365
int lenOfMonth = date.lengthOfMonth(); // 30

The class has a lot of methods to add/subtract/alter a day, month and year:

LocalDate date = LocalDate.of(2017, 1, 1); // 2017-01-01 (1 January 2017)

LocalDate tomorrow = date.plusDays(1);    // 2017-01-02 (2 January 2017)
LocalDate yesterday = date.minusDays(1);  // 2016-12-31 (31 December 2016)
LocalDate inTwoYears = date.plusYears(2); // 2019-12-01 (1 January 2019)
LocalDate in2016 = date.withYear(2016);   // 2016-01-01 (1 January 2016)

These methods always return a new instance of the class (Immutability).

As you can see, the LocalDate class provides a lot of usable methods for working with dates.

How did you like the theory?
Report a typo