Sub topic 6
DayOfWeek, Month, YearMonth, and MonthDay
A full date such as 2024-11-05 is not always what you need. Sometimes you only care about the day of the week, as in "the shop is closed on Sundays." Sometimes you want only a month and a year, such as a credit card that expires in August 2025. And sometimes you want a month and a day with no year, like a birthday that comes back every year.
The java.time package has a small type for each of these cases. This chapter covers four of them: DayOfWeek, Month, YearMonth, and MonthDay.
Why Use Smaller Types?
A type is the kind of value a variable holds. If you store a birthday as a full LocalDate, you have to make up a year, and that fake year can confuse anyone who reads the code later. A smaller type holds only the parts you mean, so the code says exactly what it means.
| Type | What it holds | Example value | Printed as |
|---|---|---|---|
| `DayOfWeek` | A day of the week | Tuesday | `TUESDAY` |
| `Month` | A month of the year | February | `FEBRUARY` |
| `YearMonth` | A year and a month | February 2024 | `2024-02` |
| `MonthDay` | A month and a day | February 29 | `--02-29` |
DayOfWeek: The Seven Days
DayOfWeek is an enum. An enum is a type with a fixed list of named values. DayOfWeek has exactly seven: MONDAY through SUNDAY.
You usually get one from a date by calling getDayOfWeek().
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.TextStyle;
import java.util.Locale;
public class Days {
public static void main(String[] args) {
LocalDate date = LocalDate.of(2024, 11, 5);
DayOfWeek day = date.getDayOfWeek();
System.out.println(day); // TUESDAY
System.out.println(day.getValue()); // 2
System.out.println(day.plus(5)); // SUNDAY
System.out.println(day.getDisplayName(TextStyle.SHORT, Locale.US)); // Tue
boolean weekend = day == DayOfWeek.SATURDAY || day == DayOfWeek.SUNDAY;
System.out.println(weekend); // false
}
}Here is what each call does:
getValue()returns a number from 1 to 7. Monday is 1 and Sunday is 7. This follows the ISO standard, an international rule for writing dates.plus(5)moves forward five days. It wraps around, so Tuesday plus 5 is Sunday.minusmoves backward in the same way.getDisplayNamegives a name a person can read.TextStyle.FULLgives "Tuesday" andTextStyle.SHORTgives "Tue". A locale is a setting for language and region, soLocale.FRENCHwould give "mardi".
Month: The Twelve Months
Month is also an enum, with twelve values from JANUARY to DECEMBER. It knows how long each month is.
import java.time.Month;
import java.time.format.TextStyle;
import java.util.Locale;
public class Months {
public static void main(String[] args) {
Month m = Month.FEBRUARY;
System.out.println(m.getValue()); // 2
System.out.println(m.length(true)); // 29
System.out.println(m.length(false)); // 28
System.out.println(m.maxLength()); // 29
System.out.println(m.plus(11)); // JANUARY
System.out.println(m.firstMonthOfQuarter()); // JANUARY
System.out.println(Month.of(12)); // DECEMBER
System.out.println(m.getDisplayName(TextStyle.FULL, Locale.US)); // February
}
}getValue()returns 1 for January up to 12 for December.length(boolean leapYear)returns the number of days. You passtruefor a leap year, which is a year with a February 29.maxLength()returns the most days the month can ever have.pluswraps around the year, so February plus 11 months is January.firstMonthOfQuarter()returns the first month of the three-month block the month belongs to. This helps with business reports.Month.of(12)turns a number into a month.
YearMonth: A Month in a Specific Year
YearMonth holds a year and a month with no day. Because it knows the year, it knows if February has 28 or 29 days.
import java.time.LocalDate;
import java.time.Month;
import java.time.YearMonth;
public class YearMonths {
public static void main(String[] args) {
YearMonth feb = YearMonth.of(2024, Month.FEBRUARY);
System.out.println(feb); // 2024-02
System.out.println(feb.lengthOfMonth()); // 29
System.out.println(feb.isLeapYear()); // true
System.out.println(feb.atDay(1)); // 2024-02-01
System.out.println(feb.atEndOfMonth()); // 2024-02-29
System.out.println(feb.plusMonths(1)); // 2024-03
YearMonth fromDate = YearMonth.from(LocalDate.of(2024, 11, 5));
System.out.println(fromDate); // 2024-11
}
}atDay and atEndOfMonth turn a YearMonth back into a full LocalDate. YearMonth is immutable like every java.time type, so plusMonths returns a new object and leaves feb unchanged.
Worked Example: Card Expiry
A credit card is valid through the end of the month printed on it. Here is a check that uses YearMonth.
import java.time.LocalDate;
import java.time.YearMonth;
public class CardExpiry {
static boolean isExpired(YearMonth expiry, LocalDate today) {
return YearMonth.from(today).isAfter(expiry);
}
public static void main(String[] args) {
YearMonth expiry = YearMonth.of(2025, 8);
System.out.println(isExpired(expiry, LocalDate.of(2025, 8, 31))); // false
System.out.println(isExpired(expiry, LocalDate.of(2025, 9, 1))); // true
}
}The code never has to work out how many days August has. It compares whole months, which matches the rule exactly.
MonthDay: A Date That Repeats Every Year
MonthDay holds a month and a day with no year. Birthdays and holidays are the usual uses. Its printed form starts with two dashes, --12-25, to show that the year is missing.
import java.time.LocalDate;
import java.time.Month;
import java.time.MonthDay;
public class MonthDays {
public static void main(String[] args) {
MonthDay birthday = MonthDay.of(Month.FEBRUARY, 29);
System.out.println(birthday); // --02-29
System.out.println(birthday.isValidYear(2023)); // false
System.out.println(birthday.isValidYear(2024)); // true
System.out.println(birthday.atYear(2023)); // 2023-02-28
System.out.println(birthday.atYear(2024)); // 2024-02-29
MonthDay christmas = MonthDay.of(12, 25);
MonthDay today = MonthDay.from(LocalDate.of(2024, 12, 25));
System.out.println(today.equals(christmas)); // true
}
}isValidYeartells you whether the month and day exist in that year.atYearbuilds aLocalDate. If the day does not exist that year, it uses the last valid day of the month, so February 29 becomes February 28 in 2023.MonthDay.from(date)drops the year from a date. This lets you ask "is today a holiday?" with oneequalscall.
Common Mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Assuming Sunday is day 1 | Weekday numbers are off by one | In java.time, Monday is 1 and Sunday is 7 |
| Using month numbers from 0 to 11 | Wrong month or an exception | Months run from 1 to 12 |
| Storing a birthday as a `LocalDate` with a fake year | Confusing data and wrong comparisons | Use `MonthDay` |
| Hard-coding 28 days for February | Wrong in leap years | Use `YearMonth.lengthOfMonth()` |
| Forgetting `plusMonths` returns a new object | The variable keeps its old value | Assign the result to a variable |
Exercises
Exercise
What does DayOfWeek.SATURDAY.plus(3) return, and what does DayOfWeek.SATURDAY.getValue() return?
Show answer
plus(3) wraps past Sunday and returns TUESDAY. getValue() returns 6, because Monday is 1 and Saturday is the sixth day.
Exercise
Write a line of Java that prints the last date of February 2100. Is 2100 a leap year?
Show answer
System.out.println(YearMonth.of(2100, 2).atEndOfMonth()); prints 2100-02-28. 2100 is not a leap year: it divides by 100 but not by 400.
Exercise
Someone was born on February 29. Your app sends a greeting on their birthday every year. Which type should you store, and what date does atYear(2025) give?
Show answer
Store a MonthDay such as MonthDay.of(2, 29). Calling atYear(2025) returns 2025-02-28, because 2025 has no February 29.
Exercise
Which type fits each value: (a) "the gym is closed on Wednesdays", (b) "the report for March 2024", (c) "New Year's Day"?
Show answer
(a) DayOfWeek.WEDNESDAY, (b) YearMonth.of(2024, 3), (c) MonthDay.of(1, 1).