Java 8 – LocalDate with method details and examples

In this article, we will discuss about newly introduced LocalDate in Java 1.8 version for dealing with date in program with ease and convenience.

Prior to introducing LocalDate and LocalTime in Java 1.8 version, we have to deal with java.util.Date, java.util.Calendar, java.sql.Timestamp, java.sql.Time, java.util.TimeZone for date/time handling in Java which isn’t easy & straight-forward and there are few issues as mentioned below,

  • Thread-safety :- Existing Date/Time classes and its methods aren’t thread-safe and hence it’s not convenient to handle in concurrent/parallel environment
  • Not so-easy API design :- Existing Date/Time classes’ methods aren’t convenient to use in day-to-day programmer’s coding or development
  • Time-zone settings :- Developers or Programmer’s life becomes difficult while dealing with time zone settings in programs

Let’s move forward and discuss about java.time.LocalDate introduced in Java 1.8 version

1. LocalDate :

  • There are 3 ways to get/form a LocalDate,
    1. First is to get current system date using static factory method now()
    2. Second is to form a LocalDate using static factory method of() passing year, month and day information
    3. Third and final is to parse date in String-form to LocalDate using static factory method parse()
  • The fully qualified package/class name of LocalDate is java.time.LocalDate i.e.; LocalDate is present under java.time package
  • Class declaration for LocalDate is as follows,
package java.time;

public final class LocalDate
        implements Temporal, TemporalAdjuster, ChronoLocalDate, Serializable {
}

2. LocalDate methods or APIs :

  • Important LocalDate method details,
    • now() – get current date from the system clock in the default time-zone
    • of() – get an instance of LocalDate from a year, month and day passed
    • parse() – get an instance of LocalDate from a text string in yyyy-MM-dd format only
    • getYear() – get the Year field from LocalDate
    • getMonthValue() – get the month-of-year field from 1 to 12 from LocalDate
    • getMonth() – get the month-of-year field using the Month enum from LocalDate
    • getDayOfMonth() – get the day-of-month field from LocalDate
    • getDayOfWeek() – get the day-of-week field, which is an enum DayOfWeek from LocalDate
    • getDayOfYear() – get the day-of-year field from LocalDate
    • lengthOfMonth() – get the length of the month represented by this date/LocalDate
    • lengthOfYear() – get the length of the year represented by this date/LocalDate
    • isLeapYear() – Checks if the year is a leap year or not, according to the ISO proleptic calendar system rules
    • plusDays() – Returns a copy of invoking LocalDate with the specified number of days added
    • plusWeeks() – Returns a copy of invoking LocalDate with the specified number of weeks added
    • plusMonths() – Returns a copy of invoking LocalDate with the specified number of months added
    • plusYears() – Returns a copy of invoking LocalDate with the specified number of years added
    • minusDays() – Returns a copy of invoking LocalDate with the specified number of days subtracted
    • minusWeeks() – Returns a copy of invoking LocalDate with the specified number of weeks subtracted
    • minusMonths() – Returns a copy of invoking LocalDate with the specified number of months subtracted
    • minusYears() – Returns a copy of invoking LocalDate with the specified number of years subtracted
    • format() – Formats invoking LocalDate using the specified date formatter
    • withDayOfMonth() – Returns a copy of this LocalDateTime with the day-of-month altered
    • withMonth() – Returns a copy of this LocalDateTime with the month-of-year altered
    • withYear() – Returns a copy of this LocalDateTime with the year altered

3. LocalDate examples :

  1. LocalDate.now() – get current date from system clock
  2. LocalDate.of() – form LocalDate passing Year, Month and Day fields
  3. LocalDate.parse() – parse the date in String-form to LocalDate
  4. Adding day, week, month and year to LocalDate using plusDays(), plusWeeks(), plusMonths() and plusYears() methods respectively
  5. Subtracting day, week, month and year from LocalDate using minusDays(), minusWeeks(), minusMonths() and minusYears() methods respectively
  6. Formatting LocalDate in different formats using DateTimeFormatter class
  7. Altering daymonth and year fields with LocalDate using withDayOfMonth(), withMonth() and withYear() methods respectively

3.1 LocalDate.now() method – get Current System Date

  • LocalDate.now() method helps to get current system date which will be in the yyyy-MM-dd format
  • We can get year, month and day field/part from LocalDate using different methods mentioned above and then we can form our own format as required like dd.MM.yyyy

LocalDateExampleUsingNowMethod.java

package in.bench.resources.localdate.sorting;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Month;

public class LocalDateExampleUsingNowMethod {

	public static void main(String[] args) {

		// 1. get current system date
		LocalDate localDate = LocalDate.now();
		System.out.println("current system local date is = " + localDate);


		// 1.1 get YEAR part from current system date
		int year = localDate.getYear();
		System.out.println("\nYear is : " + year);


		// 1.2 get MONTH part from current system date
		int month = localDate.getMonthValue();
		System.out.println("\nMonth is : " + month);


		// 1.3 get MONTH part from current system date
		Month monthInWords = localDate.getMonth();
		System.out.println("\nMonth in Words is : " + monthInWords);


		// 1.4 get DAY part from current system date
		int day = localDate.getDayOfMonth();
		System.out.println("\nDay is : " + day);


		// 1.5 get DAY part from current system date
		DayOfWeek dayOfWeek = localDate.getDayOfWeek();
		System.out.println("\nDay of Week is : " + dayOfWeek);


		// 1.6 get DAY part from current system date
		int dayOfYear = localDate.getDayOfYear();
		System.out.println("\nDay of Year is : " + dayOfYear);


		// 1.7 get Length Of current Month part from current system date
		int lengthOfMonth = localDate.lengthOfMonth();
		System.out.println("\nLength Of current Month is : " + lengthOfMonth);


		// 1.8 get Length Of current Year part from current system date
		int lengthOfYear = localDate.lengthOfYear();
		System.out.println("\nLength Of current Year is : " + lengthOfYear);


		// 1.9 Whether current Year is leap year or Not ?
		boolean isLeapYear = localDate.isLeapYear();
		System.out.println("\nWhether current Year is leap year ? : " + isLeapYear);
	}
}

Output:

current system local date is = 2022-06-21

Year is : 2022

Month is : 6

Month in Words is : JUNE

Day is : 21

Day of Week is : TUESDAY

Day of Year is : 172

Length Of current Month is : 30

Length Of current Year is : 365

Whether current Year is leap year ? : false

3.2 LocalDate.of() method – form Date

  • Passing year, month and day field/part to LocalDate.of() method returns LocalDate which will be in the yyyy-MM-dd format
  • We can extract different fields like year, month and day from LocalDate and then form our own format as required like dd/MM/yyyy

LocalDateExampleUsingOfMethod.java

package in.bench.resources.localdate.sorting;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Month;

public class LocalDateExampleUsingOfMethod {

	public static void main(String[] args) {

		// 1. form Republic Day date
		LocalDate republicDate = LocalDate.of(1950, Month.JANUARY, 26);
		System.out.println("Republic Day date is = " + republicDate);


		// 1.1 get YEAR part from Republic Day date
		int year = republicDate.getYear();
		System.out.println("\nYear is : " + year);


		// 1.2 get MONTH part from Republic Day date
		int month = republicDate.getMonthValue();
		System.out.println("\nMonth is : " + month);


		// 1.3 get MONTH part from Republic Day date
		Month monthInWords = republicDate.getMonth();
		System.out.println("\nMonth in Words is : " + monthInWords);


		// 1.4 get DAY part from Republic Day date
		int day = republicDate.getDayOfMonth();
		System.out.println("\nDay is : " + day);


		// 1.5 get DAY part from Republic Day date
		DayOfWeek dayOfWeek = republicDate.getDayOfWeek();
		System.out.println("\nDay of Week is : " + dayOfWeek);


		// 1.6 get DAY part from Republic Day date
		int dayOfYear = republicDate.getDayOfYear();
		System.out.println("\nDay of Year is : " + dayOfYear);


		// 1.7 get Length Of Republic Day date Month
		int lengthOfMonth = republicDate.lengthOfMonth();
		System.out.println("\nLength Of Republic Day Month is : " + lengthOfMonth);


		// 1.8 get Length Of Republic Day date Year
		int lengthOfYear = republicDate.lengthOfYear();
		System.out.println("\nLength Of Republic Day Year is : " + lengthOfYear);


		// 1.9 Whether republic day Year is leap year or Not ?
		boolean isLeapYear = republicDate.isLeapYear();
		System.out.println("\nWhether Republic Year is leap year ? : " + isLeapYear);
	}
}

Output:

Republic Day date is = 1950-01-26

Year is : 1950

Month is : 1

Month in Words is : JANUARY

Day is : 26

Day of Week is : THURSDAY

Day of Year is : 26

Length Of Republic Day Month is : 31

Length Of Republic Day Year is : 365

Whether Republic Year is leap year ? : false

3.3 LocalDate.parse() method – get Date in String-form

  • Sometimes, we need to parse date passed in String-form to LocalDate, for that we can use LocalDate.parse() method which will return LocalDate in yyyy-MM-dd format
  • While parsing Date value in String-form should be in yyyy-MM-dd format only, otherwise java.time.format.DateTimeParseException will be thrown

LocalDateExampleUsingParseMethod.java

package in.bench.resources.localdate.sorting;

import java.time.LocalDate;

public class LocalDateExampleUsingParseMethod {

	public static void main(String[] args) {

		// 1. Republic-Day date
		String republicDayDate = "1950-01-26";


		// 1.1 convert/parse to dateInString to LocalDate
		LocalDate republicDate = LocalDate.parse(republicDayDate);


		// 1.2 print to console
		System.out.println("1. Parsed Republic-Day date is - " + republicDate);



		// 2. Independence-Day date
		String independenceDayDate = "1947-08-15";


		// 2.1 convert/parse to dateInString to LocalDate
		LocalDate independenceDate = LocalDate.parse(independenceDayDate);


		// 2.2 print to console
		System.out.println("\n2. Parsed Independence-Day date is - " + independenceDate);
	}
}

Output:

1. Parsed Republic-Day date is - 1950-01-26

2. Parsed Independence-Day date is - 1947-08-15

3.4 Adding Day/Week/Month/Year to LocalDate :

  1. Add 5 Days to current system LocalDate using plusDays() method
  2. Add 2 Weeks to current system LocalDate using plusWeeks() method
  3. Add 3 Months to current system LocalDate using plusMonths() method
  4. Add 1 Year to current system LocalDate using plusYears() method

AddWithLocalDate.java

package in.bench.resources.localdate.sorting;

import java.time.LocalDate;

public class AddWithLocalDate {

	public static void main(String[] args) {

		// 1. get current system date
		LocalDate localDate = LocalDate.now();
		System.out.println("Current System Date is - " + localDate);


		// 1.1 add 5 days with current system date
		LocalDate add_5_Days = localDate.plusDays(5);
		System.out.println("\nAfter adding 5 Days to Current System Date is - " 
				+ add_5_Days);


		// 1.2 add 2 weeks to current system date
		LocalDate add_2_Weeks = localDate.plusWeeks(2);
		System.out.println("\nAfter adding 2 Weeks to Current System Date is - " 
				+ add_2_Weeks);


		// 1.3 add 3 months to current system date
		LocalDate add_3_Months = localDate.plusMonths(3);
		System.out.println("\nAfter adding 3 Months to Current System Date is - " 
				+ add_3_Months);


		// 1.4 add 1 year to current system date
		LocalDate add_1_Year = localDate.plusYears(1);
		System.out.println("\nAfter adding 1 Year to Current System Date is - " 
				+ add_1_Year);
	}
}

Output:

Current System Date is - 2022-06-21

After adding 5 Days to Current System Date is - 2022-06-26

After adding 2 Weeks to Current System Date is - 2022-07-05

After adding 3 Months to Current System Date is - 2022-09-21

After adding 1 Year to Current System Date is - 2023-06-21

3.5 Subtracting Day/Week/Month/Year from LocalDate :

  1. Subtract 5 Days from current system LocalDate using minusDays() method
  2. Subtract 2 Weeks from current system LocalDate using minusWeeks() method
  3. Subtract 3 Months from current system LocalDate using minusMonths() method
  4. Subtract 1 Year from current system LocalDate using minusYears() method

SubtractFromLocalDate.java

package in.bench.resources.localdate.sorting;

import java.time.LocalDate;

public class SubtractFromLocalDate {

	public static void main(String[] args) {

		// 1. get current system date
		LocalDate localDate = LocalDate.now();
		System.out.println("Current System Date is - " + localDate);


		// 1.1 subtract 5 days from current system date
		LocalDate subtract_5_Days = localDate.minusDays(5);
		System.out.println("\nAfter subtracting 5 Days from Current System Date is - " 
				+ subtract_5_Days);


		// 1.2 subtract 2 weeks from current system date
		LocalDate subtract_2_Weeks = localDate.minusWeeks(2);
		System.out.println("\nAfter subtracting 2 Weeks from Current System Date is - " 
				+ subtract_2_Weeks);


		// 1.3 subtract 3 months from current system date
		LocalDate subtract_3_Months = localDate.minusMonths(3);
		System.out.println("\nAfter subtracting 3 Months from Current System Date is - " 
				+ subtract_3_Months);


		// 1.4 subtract 1 year from current system date
		LocalDate subtract_1_Year = localDate.minusYears(1);
		System.out.println("\nAfter subtracting 1 Year from Current System Date is - " 
				+ subtract_1_Year);
	}
}

Output:

Current System Date is - 2022-06-21

After subtracting 5 Days from Current System Date is - 2022-06-16

After subtracting 2 Weeks from Current System Date is - 2022-06-07

After subtracting 3 Months from Current System Date is - 2022-03-21

After subtracting 1 Year from Current System Date is - 2021-06-21

3.6 Formatting LocalDate using DateTimeFormatter:

  • We can convert default ISO_LOCAL_DATE LocalDate format yyyy-MM-dd to any formats using LocalDate.format() method by passing DateTimeFormatter class as argument with required pattern in String-form
  • In this illustration, we are using 4 different custom formats as mentioned below,
    1. DateTimeFormatter.ofPattern(“dd.MM.yyyy“)
    2. DateTimeFormatter.ofPattern(“dd-MMM-yyyy“)
    3. DateTimeFormatter.ofPattern(“dd.M.yy“)
    4. DateTimeFormatter.ofPattern(“dd/MMM/yy“)

FormattingLocalDateUsingFormatMethod.java

package in.bench.resources.localdate.sorting;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class FormattingLocalDateUsingFormatMethod {

	public static void main(String[] args) {


		// 1. get current system date
		LocalDate localDate = LocalDate.now();
		System.out.println("1. Today's date in ISO_LOCAL_DATE format is = " + localDate);


		// 1.1 format to dd.MM.yyyy
		String formattedDate = localDate.format(DateTimeFormatter.ofPattern("dd.MM.yyyy"));
		System.out.println("\n1.1 LocalDate in dd.MM.yyyy format is = " + formattedDate);


		// 1.2 format to dd-MMM-yyyy
		String formattedDate2 = localDate.format(DateTimeFormatter.ofPattern("dd-MMM-yyyy"));
		System.out.println("\n1.2 LocalDate in dd-MMM-yyyy format is = " + formattedDate2);


		// 2. form LocalDate using of() passing year, month and day
		LocalDate localDate2 = LocalDate.of(2022, 05, 27);
		System.out.println("\n\n2. LocalDate in ISO_LOCAL_DATE format is = " + localDate2);


		// 1.1 format to dd.M.yy
		String formattedDate3 = localDate2.format(DateTimeFormatter.ofPattern("dd.M.yy"));
		System.out.println("\n2.1 LocalDate in dd.M.yy format is = " + formattedDate3);


		// 1.2 format to dd/MMM/yy
		String formattedDate4 = localDate2.format(DateTimeFormatter.ofPattern("dd/MMM/yy"));
		System.out.println("\n2.2 LocalDate in dd/MMM/yy format is = " + formattedDate4);
	}
}

Output:

1. Today's date in ISO_LOCAL_DATE format is = 2022-06-21

1.1 LocalDate in dd.MM.yyyy format is = 21.06.2022

1.2 LocalDate in dd-MMM-yyyy format is = 21-Jun-2022


2. LocalDate in ISO_LOCAL_DATE format is = 2022-05-27

2.1 LocalDate in dd.M.yy format is = 27.5.22

2.2 LocalDate in dd/MMM/yy format is = 27/May/22

3.7 Altering Day/Month/Year fields with LocalDate:

  • Altering Day, Month and Year field/part of LocalDate is possible with the help below methods,
    • withDayOfMonth() – This method alters day-of-month part/field of the invoking LocalDate
    • withMonth() – This method alters month-of-year part/field of the invoking LocalDate
    • withYear() – This method alters year part/field of the invoking LocalDate

AlterLocalDate.java

package in.bench.resources.localdate.sorting;

import java.time.LocalDate;

public class AlterLocalDate {

	public static void main(String[] args) {

		// 1. get current system Date
		LocalDate localDate = LocalDate.now();
		System.out.println("1. Current Date/time in ISO_LOCAL_DATE format is = " 
				+ localDate);


		// 1.1 alter day part to current system Date
		LocalDate dateAltered = localDate.withDayOfMonth(27);
		System.out.println("\n1.1 Day (27) altered in current system Date/time is = " 
				+ dateAltered);


		// 1.2 alter month part to current system Date
		LocalDate monthAltered = localDate.withMonth(7);
		System.out.println("\n1.2 Month (7) altered in current system Date/time is = " 
				+ monthAltered);


		// 1.3 alter year part to current system Date
		LocalDate yearAltered = localDate.withYear(2023);
		System.out.println("\n1.3 Year (2023) altered in current system Date/time is = " 
				+ yearAltered);
	}
}

Output:

1. Current Date/time in ISO_LOCAL_DATE format is = 2022-06-25

1.1 Day (27) altered in current system Date/time is = 2022-06-27

1.2 Month (7) altered in current system Date/time is = 2022-07-25

1.3 Year (2023) altered in current system Date/time is = 2023-06-25

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java 8 - LocalTime with method details and examples
Java 8 - How to Sort List by java.time.LocalDateTime in 4 ways ?