Dates with LocalDate
30 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)A LocalDate is a plain calendar date, such as 15 March 2024, with no time of day and no time zone. Exam dates, fee due dates and dates of birth are all dates of this kind.
Why a separate date class exists
LocalDate is an immutable date without time or time zone, such as 2026-10-23, from the java.time package.
Many values in an app are only a date, with no time of day, so they need a date type of their own. A library book is due on 29 March. A student was born on 20 August 2005. Nobody cares about the hour or the minute here.
Before Java 8, Java had java.util.Date, which held a moment in milliseconds, not a calendar date. To store "15 March" you had to pick a fake time like midnight, and the date could shift when the time zone changed. Its months also started from 0, so March was 2.
Java 8 added the java.time package. A package is a folder of related classes. Its LocalDate holds just a year, a month and a day. "Local" means it is the date on a wall calendar, not linked to any time zone.
import java.time.LocalDate; or bring in the whole package with import java.time.*;.Three ways to get a LocalDate
LocalDate has no public constructor, so new LocalDate(...) does not compile. You use factory methods: static methods that build and return an object for you.
Example 1 · Three ways to create the same date
import java.time.LocalDate;import java.time.Month;
public class CreateDateDemo { public static void main(String[] args) { LocalDate a = LocalDate.of(2024, 3, 15); LocalDate b = LocalDate.of(2024, Month.MARCH, 15); LocalDate c = LocalDate.parse("2024-03-15");
System.out.println("of with numbers: " + a); System.out.println("of with Month: " + b); System.out.println("parse: " + c); System.out.println("a equals c? " + a.equals(c));
// In a real app: LocalDate today = LocalDate.now(); LocalDate examDay = LocalDate.of(2024, 4, 1); System.out.println("Exam day: " + examDay); }}of with numbers: 2024-03-15 of with Month: 2024-03-15 parse: 2024-03-15 a equals c? true Exam day: 2024-04-01
What this code does
- All three lines build the same date, and printing a
LocalDatealways shows the ISO formyyyy-MM-dd.equalscompares the year, month and day, soaandcare equal. LocalDate.now()would read today's date from the computer, so its output changes daily. Lessons and tests use fixed dates likeexamDayinstead.
LocalDate.now()gives today's date from the computer's clock. It changes every day, so this lesson uses fixed dates to keep outputs the same.LocalDate.of(2024, 3, 15)builds a date from numbers.LocalDate.of(2024, Month.MARCH, 15)does the same with theMonthenum.LocalDate.parse("2024-03-15")reads text in the ISO formatyyyy-MM-dd: a four-digit year, a two-digit month, a two-digit day.- Printing a
LocalDateshows that same ISO form,2024-03-15. Other display styles come later, in the formatting lesson.
LocalDate.of(2023, 2, 29) throws DateTimeException, and LocalDate.parse("15-03-2024") throws DateTimeParseException.Reading the parts of a date
Getter methods read each part: getYear(), getMonthValue() (a number 1 to 12), getMonth() (a Month enum such as MARCH), getDayOfMonth(), getDayOfWeek() (a DayOfWeek enum such as FRIDAY) and getDayOfYear() (1 to 366).
Example 2 · Reading the parts of an exam date
import java.time.LocalDate;
public class ExamDateDemo { public static void main(String[] args) { LocalDate exam = LocalDate.parse("2024-03-15");
System.out.println("Year: " + exam.getYear()); System.out.println("Month number: " + exam.getMonthValue()); System.out.println("Month: " + exam.getMonth()); System.out.println("Day: " + exam.getDayOfMonth()); System.out.println("Day of week: " + exam.getDayOfWeek()); System.out.println("Day of year: " + exam.getDayOfYear()); System.out.println("Days in month: " + exam.lengthOfMonth()); }}Year: 2024 Month number: 3 Month: MARCH Day: 15 Day of week: FRIDAY Day of year: 75 Days in month: 31
What this code does
getMonthValue()returns a plain number (3), whilegetMonth()returns theMonthenum (MARCH). The same goes forgetDayOfWeek(), which returnsFRIDAY.- 15 March 2024 is day 75 of the year: 31 days of January, 29 of February (a leap year) and 15 of March.
Example 3 · Leap years and February
import java.time.LocalDate;
public class LeapYearDemo { public static void main(String[] args) { int[] years = {2023, 2024, 1900, 2000}; for (int y : years) { LocalDate feb = LocalDate.of(y, 2, 1); System.out.println(y + ": leap=" + feb.isLeapYear() + ", February has " + feb.lengthOfMonth() + " days, year has " + feb.lengthOfYear()); } }}2023: leap=false, February has 28 days, year has 365 2024: leap=true, February has 29 days, year has 366 1900: leap=false, February has 28 days, year has 365 2000: leap=true, February has 29 days, year has 366
What this code does
- A year divisible by 4 is a leap year, except century years, which must also be divisible by 400. So 1900 is not a leap year, but 2000 is.
- You never write this rule yourself:
isLeapYear(),lengthOfMonth()andlengthOfYear()already know it.
A date also knows its calendar. lengthOfMonth() gives 28, 29, 30 or 31. lengthOfYear() gives 365 or 366. isLeapYear() is true in a leap year: a year divisible by 4, except century years, which must be divisible by 400. So 2024 and 2000 are leap years, but 2023 and 1900 are not.
Months are 1 to 12, and the Month enum
In java.time, January is 1 and December is 12, just like on paper. LocalDate.of(2024, 3, 15) is 15 March. The old Calendar class counted months from 0, which caused many bugs.
Example 4 · The Month and DayOfWeek enums
import java.time.DayOfWeek;import java.time.LocalDate;import java.time.Month;
public class MonthEnumDemo { public static void main(String[] args) { Month m = Month.of(12); System.out.println("Month 12 is " + m); System.out.println("Next month: " + m.plus(1)); System.out.println("MARCH value: " + Month.MARCH.getValue()); System.out.println("February in a leap year: " + Month.FEBRUARY.length(true));
DayOfWeek d = LocalDate.of(2024, 3, 17).getDayOfWeek(); System.out.println("17 March 2024 is " + d + ", number " + d.getValue()); System.out.println("Weekend? " + (d == DayOfWeek.SATURDAY || d == DayOfWeek.SUNDAY)); }}Month 12 is DECEMBER Next month: JANUARY MARCH value: 3 February in a leap year: 29 17 March 2024 is SUNDAY, number 7 Weekend? true
What this code does
Month.of(12)isDECEMBERbecause months run from 1 to 12.plus(1)onDECEMBERwraps round toJANUARY.DayOfWeeknumbers Monday as 1 and Sunday as 7. Enum values are compared with==, which makes a weekend check short and safe.
The Month enum names the twelve months: Month.JANUARY to Month.DECEMBER. An enum is a fixed set of named constants. Month.MARCH.getValue() is 3, Month.of(3) is MARCH, and Month.DECEMBER.plus(1) wraps round to JANUARY. Month.FEBRUARY.length(true) gives 29, the length in a leap year. DayOfWeek works the same way, with MONDAY as 1 and SUNDAY as 7.
Trap: plusDays returns a new date
Every java.time object is immutable: once created, it never changes. Methods such as plusDays(14), plusWeeks, plusMonths, plusYears and minusDays do not touch the date you call them on. They build and return a new date.
Example 5 · Trap: ignoring the result of plusDays
import java.time.LocalDate;
public class DueDateDemo { public static void main(String[] args) { LocalDate issued = LocalDate.of(2024, 3, 15);
issued.plusDays(14); // result thrown away System.out.println("Wrong due date: " + issued);
LocalDate due = issued.plusDays(14); // keep the new date System.out.println("Issued: " + issued); System.out.println("Due: " + due); System.out.println("Due day: " + due.getDayOfWeek()); System.out.println("A week before due: " + due.minusWeeks(1)); }}Wrong due date: 2024-03-15 Issued: 2024-03-15 Due: 2024-03-29 Due day: FRIDAY A week before due: 2024-03-22
What this code does
plusDays(14)builds a new date and returns it. The first call ignores that return value, soissuedstill shows 15 March and the book has no real due date.- Storing the result in
duegives 29 March.issuedis unchanged even then, because aLocalDatecan never be changed after it is created.
So issued.plusDays(14); on its own line does nothing useful: the new date is thrown away and issued stays the same. The compiler does not warn you. Always keep the result: LocalDate due = issued.plusDays(14);. Immutability is a good thing. You can pass a date to any method or share it in a list, and no one can change it behind your back.
Predict the output
Which date does it print?
Read each program and pick the output. LocalDate never changes.
Round 1 of 3
A due date, with plusDays called but not stored.
Example 6 · Bad dates fail fast
import java.time.DateTimeException;import java.time.LocalDate;import java.time.format.DateTimeParseException;
public class BadDateDemo { public static void main(String[] args) { try { LocalDate d = LocalDate.of(2023, 2, 29); System.out.println(d); } catch (DateTimeException e) { System.out.println("of failed: " + e.getMessage()); }
try { LocalDate d = LocalDate.parse("15-03-2024"); System.out.println(d); } catch (DateTimeParseException e) { System.out.println("parse failed: " + e.getMessage()); }
System.out.println("parse ok: " + LocalDate.parse("2024-02-29")); }}of failed: Invalid date 'February 29' as '2023' is not a leap year parse failed: Text '15-03-2024' could not be parsed at index 0 parse ok: 2024-02-29
What this code does
- 2023 is not a leap year, so 29 February 2023 does not exist and
ofthrowsDateTimeExceptionwith a clear message. Java never rolls it over to 1 March by itself. parsewith no pattern accepts onlyyyyy-MM-dd. Text like15-03-2024fails at index 0, the first character it could not read.DateTimeParseExceptionis a kind ofDateTimeException.
Next step
Check your understanding
11 quick questions