Java LocalDate
The Java LocalDate class is an immutable and thread-safe class that represents a date with a default format of yyyy-MM-dd. The LocalDate class can be used to store a date in the following format “22nd April 2019”.
How to use
This class does not handle or represent a time or time-zone, we can use LocalDate class to store information like birthdays. Try the following examples to better understand –
Day example
Following is the simple example that shows how you add/subtract days in the current date and print them.
import java.time.LocalDate; public class LocalDateDayExample { public static void main(String[] args) { LocalDate currentDate = LocalDate.now(); // Get current date System.out.println("Today: " + currentDate); // Get yesterday's date (Subtract 1 day in current date) currentDate = LocalDate.now().minusDays(1); System.out.println("Yesterday: " + currentDate); // Get tommorow's date (Add 1 day in current date) currentDate = LocalDate.now().plusDays(1); System.out.println("Tommorow: " + currentDate); } }
Month example
Following is the simple example that shows how you add/subtract months in the current month and print them.
import java.time.LocalDate; public class LocalDateMonthExample { public static void main(String[] args) { LocalDate currentDate = LocalDate.now(); // Get current month System.out.println("Current month: " + currentDate.getMonth()); // Previous month currentDate = LocalDate.now().minusMonths(1); System.out.println("Previous month: " + currentDate.getMonth()); // Next month currentDate = LocalDate.now().plusMonths(1); System.out.println("Next month: " + currentDate.getMonth()); } }
Year example
Similar to the previous two examples, you also have the option to work with years. Following is the simple example that shows how you add/subtract years in the current year and print them.
import java.time.LocalDate; public class LocalDateYearExample { public static void main(String[] args) { LocalDate currentDate = LocalDate.now(); // Get current month System.out.println("Current year: " + currentDate.getYear()); // Previous year currentDate = LocalDate.now().minusYears(1); System.out.println("Previous year: " + currentDate.getYear()); // Next year currentDate = LocalDate.now().plusYears(1); System.out.println("Next year: " + currentDate.getYear()); } }
Leap or not example
Following is the example program to check if the given year is a leap year or not.
import java.time.LocalDate; public class LocalDateLeapYear { public static void main(String[] args) { // Check current year is leap year or not LocalDate localDate1 = LocalDate.now(); System.out.println("Leap year: " + localDate1.isLeapYear()); // Check given year is leap year or not LocalDate localDate2 = LocalDate.of(2012, 01, 01); System.out.println("Leap year: " + localDate2.isLeapYear()); } }