First and Last Day of Week, Month or Year in Java

Get the first and last day of week, month or year in Java with TemporalAdjusters, WeekFields for locales, YearMonth and quarter boundaries.

Ten days from April 20 to April 29, 2024 with three week bands for a Monday, Sunday and Saturday week start, and the month and year boundaries of April 26, 2024

To get the first and last day of week, month or year in Java, we call with() on a LocalDate and pass an adjuster from the TemporalAdjusters class, such as firstDayOfMonth(), lastDayOfMonth() or previousOrSame(DayOfWeek.MONDAY). The month and year boundaries are fixed, whereas the week boundaries depend on which day starts the week in our app.

Reports, invoices and timesheets need these dates all the time. A billing job needs the first and last day of last month, and a timesheet page shows the dates from Monday to Sunday of the current week.

The following example uses Friday, April 26, 2024 as the given date and shows each boundary with its result as a comment.

LocalDate today = LocalDate.of(2024, 4, 26);                                                 // Friday

LocalDate firstDayOfWeek = today.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));   // 2024-04-22
LocalDate lastDayOfWeek = today.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));        // 2024-04-28

LocalDate usWeekStart = today.with(WeekFields.of(Locale.US).dayOfWeek(), 1);                 // 2024-04-21
LocalDate usWeekEnd = today.with(WeekFields.of(Locale.US).dayOfWeek(), 7);                   // 2024-04-27

LocalDate firstDayOfMonth = today.with(TemporalAdjusters.firstDayOfMonth());                 // 2024-04-01
LocalDate lastDayOfMonth = today.with(TemporalAdjusters.lastDayOfMonth());                   // 2024-04-30

LocalDate firstDayOfYear = today.with(TemporalAdjusters.firstDayOfYear());                   // 2024-01-01
LocalDate lastDayOfYear = today.with(TemporalAdjusters.lastDayOfYear());                     // 2024-12-31

Notice that the month and year results never depend on any setting, whereas the US week runs from Sunday to Saturday and gives different dates. We go through each boundary in turn, including the week start of a locale, YearMonth, the previous month and the quarter, and finish with turning the dates into timestamps for a database query.

1. The TemporalAdjusters Class and with()

The class TemporalAdjusters in java.time.temporal has ready-made adjusters as static methods. Each method returns a TemporalAdjuster, which is an object that takes a date and returns a new, adjusted date, in the style of the strategy design pattern.

Ten days from April 20 to April 29, 2024 with three week bands for a Monday, Sunday and Saturday week start, and the month and year boundaries of April 26, 2024
One date belongs to three different weeks, but always to the same month and year

The adjusters for this topic and their results for 2024-04-26 are in one table, so we can pick the right one at a glance.

AdjusterResult for 2024-04-26
firstDayOfMonth()2024-04-01
lastDayOfMonth()2024-04-30
firstDayOfNextMonth()2024-05-01
firstDayOfYear()2024-01-01
lastDayOfYear()2024-12-31
firstDayOfNextYear()2025-01-01
previousOrSame(DayOfWeek.MONDAY)2024-04-22
nextOrSame(DayOfWeek.SUNDAY)2024-04-28
firstInMonth(DayOfWeek.MONDAY)2024-04-01
lastInMonth(DayOfWeek.FRIDAY)2024-04-26

We apply an adjuster with temporal.with(adjuster), where temporal can be a LocalDate, a LocalDateTime or a ZonedDateTime. The date classes are immutable, so with() returns a new object and the original date stays the same. Custom adjusters and the full list are in the TemporalAdjusters guide.

2. First and Last Day of Week

For a week that starts on Monday, which is the ISO-8601 rule used in most of Europe, we use two adjusters. If the app uses another day as the start of the week, we pass that day instead.

  • The method previousOrSame(DayOfWeek) returns the given date when it already falls on that day of the week, or else the closest earlier date with that day of the week.
  • The method nextOrSame(DayOfWeek) returns the given date when it already falls on that day of the week, or else the closest later date with that day of the week.
LocalDate today = LocalDate.of(2024, 4, 26);
LocalDate firstDayOfWeek = today.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));   // 2024-04-22
LocalDate lastDayOfWeek = today.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));        // 2024-04-28

LocalDate monday = LocalDate.of(2024, 4, 22);
LocalDate sameMonday = monday.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));      // 2024-04-22
LocalDate mondayBefore = monday.with(TemporalAdjusters.previous(DayOfWeek.MONDAY));          // 2024-04-15

LocalDate newYear = LocalDate.of(2025, 1, 1);
LocalDate weekStart = newYear.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));      // 2024-12-30

On a Monday, previousOrSame() keeps the date, whereas previous() moves back a whole week, so the week boundaries always use the “OrSame” variants. A week can also cross a year boundary, as the last line shows for January 1, 2025.

2.1. First Day of Week by Locale

A time-tracking app for a team in the US and Germany shows “this week” on its home page. People in the US expect the week from Sunday to Saturday, whereas people in Germany expect Monday to Sunday. The class WeekFields holds the week rules of a locale, and its dayOfWeek() field counts the days from the first day of that week, so the values 1 and 7 give the first and the last day.

LocalDate today = LocalDate.of(2024, 4, 26);
WeekFields us = WeekFields.of(Locale.US);
DayOfWeek usFirstDay = us.getFirstDayOfWeek();                                         // SUNDAY
LocalDate usWeekStart = today.with(us.dayOfWeek(), 1);                                 // 2024-04-21
LocalDate usWeekEnd = today.with(us.dayOfWeek(), 7);                                   // 2024-04-27
LocalDate germanWeekStart = today.with(WeekFields.of(Locale.GERMANY).dayOfWeek(), 1);  // 2024-04-22
LocalDate isoWeekStart = today.with(WeekFields.ISO.dayOfWeek(), 1);                    // 2024-04-22

The first day of the week comes from the Unicode CLDR locale data in the JDK. On JDK 25, a few common locales give these results.

LocaleFirst day of weekWeek of 2024-04-26
Locale.US, Locale.CANADA, Locale.JAPAN, en-IN, pt-BRSUNDAY2024-04-21 to 2024-04-27
Locale.UK, Locale.GERMANY, Locale.FRANCE, Locale.CHINAMONDAY2024-04-22 to 2024-04-28
ar-EG, fa-IRSATURDAY2024-04-20 to 2024-04-26
WeekFields.ISOMONDAY2024-04-22 to 2024-04-28

A user can also choose the first day of the week in the language tag with the Unicode extension fw, and WeekFields.of() honors it. For example, the tag en-US-u-fw-mon keeps US English text but starts the week on Monday.

Locale usMondayWeek = Locale.forLanguageTag("en-US-u-fw-mon");
DayOfWeek firstDay = WeekFields.of(usMondayWeek).getFirstDayOfWeek();   // MONDAY

On a server, we pass the user’s locale or a fixed WeekFields value, and never rely on Locale.getDefault(). The default locale is the locale of the machine, so the same code gives a different week on a US server and on a German server.

3. First Day and Last Day of Month

The adjusters firstDayOfMonth() and lastDayOfMonth() return the first and the last day of the month in which the given date falls. The adjuster for the last day uses the length of every month, including February in leap years, so we never hard-code 28, 30 or 31.

LocalDate today = LocalDate.of(2024, 4, 26);
LocalDate firstDayOfMonth = today.with(TemporalAdjusters.firstDayOfMonth());                   // 2024-04-01
LocalDate lastDayOfMonth = today.with(TemporalAdjusters.lastDayOfMonth());                     // 2024-04-30
LocalDate leapFebruary = LocalDate.of(2024, 2, 10).with(TemporalAdjusters.lastDayOfMonth());   // 2024-02-29
LocalDate normalFebruary = LocalDate.of(2023, 2, 10).with(TemporalAdjusters.lastDayOfMonth()); // 2023-02-28

The method withDayOfMonth() gives the same results without an adjuster. We pass 1 for the first day and the value of lengthOfMonth() for the last day.

LocalDate today = LocalDate.of(2024, 4, 26);
LocalDate firstDay = today.withDayOfMonth(1);                         // 2024-04-01
LocalDate lastDay = today.withDayOfMonth(today.lengthOfMonth());      // 2024-04-30

3.1. Using YearMonth

When we have a month and a year but no day, such as a “2024-02” filter in a report, the class YearMonth is the better fit. Its methods atDay(1) and atEndOfMonth() return the first and the last LocalDate of that month.

YearMonth february = YearMonth.of(2024, 2);
LocalDate first = february.atDay(1);                                              // 2024-02-01
LocalDate last = february.atEndOfMonth();                                         // 2024-02-29
int days = february.lengthOfMonth();                                              // 29
LocalDate fromDate = YearMonth.from(LocalDate.of(2024, 4, 26)).atEndOfMonth();    // 2024-04-30

3.2. Previous Month and Weekdays in a Month

A monthly invoice job runs on the first day of a month and bills the whole previous month. We go back one month with minusMonths(1) and apply the adjusters to the result. The adjusters firstInMonth(), lastInMonth() and dayOfWeekInMonth() find a weekday inside the month, such as the first Monday or the last Friday for a payday.

LocalDate today = LocalDate.of(2024, 4, 26);
LocalDate previousMonthStart = today.minusMonths(1).with(TemporalAdjusters.firstDayOfMonth());   // 2024-03-01
LocalDate previousMonthEnd = today.minusMonths(1).with(TemporalAdjusters.lastDayOfMonth());      // 2024-03-31
LocalDate nextMonthStart = today.with(TemporalAdjusters.firstDayOfNextMonth());                  // 2024-05-01
LocalDate firstMonday = today.with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY));            // 2024-04-01
LocalDate lastFriday = today.with(TemporalAdjusters.lastInMonth(DayOfWeek.FRIDAY));              // 2024-04-26
LocalDate secondTuesday = today.with(TemporalAdjusters.dayOfWeekInMonth(2, DayOfWeek.TUESDAY));  // 2024-04-09

4. First Day and Last Day of Year

The adjusters firstDayOfYear() and lastDayOfYear() return January 1 and December 31 of the year of the given date, and firstDayOfNextYear() returns January 1 of the following year. The class Year builds the same dates from a year number alone.

LocalDate today = LocalDate.of(2024, 4, 26);
LocalDate firstDayOfYear = today.with(TemporalAdjusters.firstDayOfYear());       // 2024-01-01
LocalDate lastDayOfYear = today.with(TemporalAdjusters.lastDayOfYear());         // 2024-12-31
LocalDate nextYearStart = today.with(TemporalAdjusters.firstDayOfNextYear());    // 2025-01-01
LocalDate yearStart = Year.of(2024).atDay(1);                                    // 2024-01-01
LocalDate yearEnd = today.withDayOfYear(today.lengthOfYear());                   // 2024-12-31

The year has no locale rules, so January 1 and December 31 are the answer for every LocalDate. The method lengthOfYear() returns 366 for a leap year such as 2024, which is why withDayOfYear(lengthOfYear()) also returns December 31.

5. First Day and Last Day of Quarter

The class TemporalAdjusters has no quarter methods, but the field IsoFields.DAY_OF_QUARTER sets the day within the quarter. The value 1 gives the first day, and the maximum of the field’s range gives the last day, which is 90, 91 or 92 depending on the quarter.

LocalDate today = LocalDate.of(2024, 4, 26);
int quarter = today.get(IsoFields.QUARTER_OF_YEAR);                                                         // 2
LocalDate quarterStart = today.with(IsoFields.DAY_OF_QUARTER, 1);                                           // 2024-04-01
LocalDate quarterEnd = today.with(IsoFields.DAY_OF_QUARTER, today.range(IsoFields.DAY_OF_QUARTER).getMaximum());   // 2024-06-30

Quarter labels such as Q2 and fiscal years that start in another month are covered in getting the current quarter start and end.

6. Using the Dates in a Date Range Query

A report often needs timestamps, not dates, for example to select the orders of April from a timestamp column. We turn the first day into a start time with atStartOfDay(). For the end, we use the first day of the next month as an exclusive limit and query with created_at >= start AND created_at < end.

LocalDate today = LocalDate.of(2024, 4, 26);
LocalDateTime start = today.with(TemporalAdjusters.firstDayOfMonth()).atStartOfDay();                 // 2024-04-01T00:00
LocalDateTime end = today.with(TemporalAdjusters.firstDayOfNextMonth()).atStartOfDay();               // 2024-05-01T00:00
LocalDateTime lastMoment = today.with(TemporalAdjusters.lastDayOfMonth()).atTime(LocalTime.MAX);      // 2024-04-30T23:59:59.999999999

We prefer the exclusive end over LocalTime.MAX, because a column with fewer fraction digits can round 23:59:59.999999999 up to the next day, as MySQL does for fractional seconds. The adjusters also work on LocalDateTime and ZonedDateTime and keep the time part, so we reset the time when we need midnight. More options are in getting the start and the end of a day.

7. First and Last Day FAQs

Searches for this topic often continue with the current month, day counts, the legacy Calendar class and week numbers.

7.1. How Do I Get the Last Day of the Current Month?

We call LocalDate.now() with a zone and apply lastDayOfMonth(). Passing a ZoneId makes the result independent of the server’s default time zone, which matters on the last evening of a month.

LocalDate lastDayOfThisMonth = LocalDate.now(ZoneId.of("UTC")).with(TemporalAdjusters.lastDayOfMonth());   // last day of the current month in UTC

7.2. How Do I Get the Number of Days in a Month?

We call lengthOfMonth() on a LocalDate or a YearMonth. For example, YearMonth.of(2024, 2).lengthOfMonth() returns 29, and LocalDate.of(2024, 4, 26).lengthOfMonth() returns 30. For the days between two dates, read counting days between dates.

7.3. How Do I Get the Last Day of the Month From a java.util.Date?

The fix is to turn the Date into a LocalDate in an explicit zone and apply the adjuster. Old code used Calendar.getActualMaximum(Calendar.DAY_OF_MONTH) for the same answer, but Calendar is mutable and depends on the default zone.

Date legacy = Date.from(Instant.parse("2024-04-26T10:00:00Z"));
LocalDate date = legacy.toInstant().atZone(ZoneId.of("UTC")).toLocalDate();       // 2024-04-26
LocalDate monthEnd = date.with(TemporalAdjusters.lastDayOfMonth());               // 2024-04-30

7.4. How Do I Get the Week Number of a Date?

We read the field weekOfWeekBasedYear() from a WeekFields object, for example today.get(WeekFields.ISO.weekOfWeekBasedYear()) returns 17 for 2024-04-26. The week number depends on the same locale rules as the first day of the week in section 2.1. To count whole weeks, read weeks between two dates.

8. Conclusion

The class TemporalAdjusters gives us ready-made adjusters for the first and the last day of a month or a year, and LocalDate.with() applies them. The month and year results are always the same for a given date, and lastDayOfMonth() handles leap years for us.

The week is different, because its first day depends on the region. We use previousOrSame() and nextOrSame() with a fixed day, or WeekFields.of(locale).dayOfWeek() when the week must follow the user’s locale. For database queries, we turn the first day into a start timestamp and use the first day of the next period as an exclusive end.

More date recipes are collected in the Java date and time guide.

9. References

Happy Learning !!

Source Code on Github

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.