i want to pass in a year and get a date back that represents the first monday of the first week
so:
A slightly different method – The date. weekday() function gives your an index of the day of the week (where Monday is 0 and Sunday is 6). You can use this value to directly calculate the which date any day of the week will fall on.
private DateTime GetFirstMondayOfYear(int year)
{
DateTime dt = new DateTime(year, 1, 1);
while (dt.DayOfWeek != DayOfWeek.Monday)
{
dt = dt.AddDays(1);
}
return dt;
}
Try this for a solution without looping:
public DateTime FirstMonday(int year)
{
DateTime firstDay = new DateTime(year, 1, 1);
return new DateTime(year, 1, (8 - (int)firstDay.DayOfWeek) % 7 + 1);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With