Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LocalDate from month and day of week in NodaTime

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.

like image 749
Matt Kline Avatar asked Dec 02 '25 02:12

Matt Kline


1 Answers

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.)

like image 119
Matt Johnson-Pint Avatar answered Dec 03 '25 19:12

Matt Johnson-Pint



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!