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.
Asked
Active
Viewed 811 times
3

Matt Kline
- 10,149
- 7
- 50
- 87
-
Sounds as if this is a duplicate: http://stackoverflow.com/questions/2136487/calculate-week-of-month-in-net – Tim Schmelter Jun 24 '14 at 14:31
-
That may be a good starting point, but note that this is using [NodaTime](http://nodatime.org/) – Matt Kline Jun 24 '14 at 14:34
-
Do you actually need to parse a string of text like the example you gave? Or do you have separate variables for each piece already? – Matt Johnson-Pint Jun 24 '14 at 15:32
-
@MattJohnson: The latter – Matt Kline Jun 24 '14 at 15:33
1 Answers
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