Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

whats the simplest way to calculate the Monday in the first week of the year

Tags:

c#

datetime

i want to pass in a year and get a date back that represents the first monday of the first week

so:

  • If a passed in 2011, i would get back Jan 3, 2011
  • If a passed in 2010, i would get back Jan 4, 2010
like image 640
leora Avatar asked Apr 14 '11 14:04

leora


People also ask

How do you get the first Monday of the month in Python?

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.


2 Answers

private DateTime GetFirstMondayOfYear(int year)
{
    DateTime dt = new DateTime(year, 1, 1);

    while (dt.DayOfWeek != DayOfWeek.Monday)
    {
        dt = dt.AddDays(1);
    }

    return dt;
}
like image 79
Steve Danner Avatar answered Nov 07 '22 20:11

Steve Danner


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);
}
like image 30
Jackson Pope Avatar answered Nov 07 '22 21:11

Jackson Pope