3

I'm looking to construct a date from a description such as "The second Monday in March, 2014". How would I go about doing so? LocalDate's FromWeekYearWeekAndDay seems like a start, but as I said, I'm hoping to provide the week of the month, not the week of the year.

Matt Kline
  • 10,149
  • 7
  • 50
  • 87

1 Answers1

3

This could most certainly be refined, but here is a function that will work:

public static LocalDate GetDay(int year, int month, IsoDayOfWeek dayOfWeek,
                                                                    int instance)
{
    int daysInMonth = CalendarSystem.Iso.GetDaysInMonth(year, month);

    var ld = new LocalDate(year, month, 1);
    if (ld.IsoDayOfWeek != dayOfWeek)
        ld = ld.Next(dayOfWeek);
    for (int i = 1; i < instance && ld.Day + 7 <= daysInMonth; i++)
        ld = ld.PlusWeeks(1);
    return ld;
}

You can pass 5 for the instance if you want the last one, which might fall on the 4th or 5th week.

Refinements might include support for other calendars, and better use of modulo math to avoid loops.

(A feature request has been filed, and may well be supported in 2.0.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575