LocalDate.onDayOfWeekInMonth constructor

LocalDate.onDayOfWeekInMonth(
  1. int year,
  2. int month,
  3. int occurrence,
  4. DayOfWeek dayOfWeek,
)

Returns the local date corresponding to a particular occurrence of a day-of-week within a year and month. For example, this method can be used to ask for 'the third Monday in April 2012'.

The returned date is always in the ISO calendar. This method is unrelated to week-years and any rules for 'business weeks' and the like - if a month begins on a Friday, then asking for the first Friday will give that day, for example.

  • year: The year of the value to return.
  • month: The month of the value to return.
  • occurrence: The occurrence of the value to return, which must be in the range 1, 5. The value 5 can be used to always return the last occurrence of the specified day-of-week, even if there are only 4 occurrences of that day-of-week in the month.
  • dayOfWeek: The day-of-week of the value to return. The date corresponding to the given year and month, on the given occurrence of the given day of week.

Implementation

factory LocalDate.onDayOfWeekInMonth(int year, int month, int occurrence, DayOfWeek dayOfWeek)
{
  // This validates year and month as well as getting us a useful date.
  LocalDate startOfMonth = LocalDate(year, month, 1);
  Preconditions.checkArgumentRange('occurrence', occurrence, 1, 5);
  Preconditions.checkArgumentRange('dayOfWeek', dayOfWeek.value, 1, 7);

  // Correct day of week, 1st week of month.
  int week1Day = dayOfWeek - startOfMonth.dayOfWeek + 1;
  if (week1Day <= 0)
  {
    week1Day += 7;
  }
  int targetDay = week1Day + (occurrence - 1) * 7;
  if (targetDay > CalendarSystem.iso.getDaysInMonth(year, month))
  {
    targetDay -= 7;
  }
  return LocalDate(year, month, targetDay);
}