12

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
leora
  • 188,729
  • 360
  • 878
  • 1,366
  • 1
    What definition of 'first week' are you using? See [this list of definitions](http://en.wikipedia.org/wiki/Week_number#Week_numbering) – Janoz Apr 14 '11 at 14:39

3 Answers3

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

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

    return dt;
}
Steve Danner
  • 21,818
  • 7
  • 41
  • 51
  • 7
    This gets the first Monday in the year, which may be what the OP wants. Note, however, that the ISO has a definition for "first week" by which the Monday of the first week in year N may actually fall in year N-1. – JSBձոգչ Apr 14 '11 at 14:43
11

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);
}
Jackson Pope
  • 14,520
  • 6
  • 56
  • 80
  • 2
    int & DayOfWeek aren't compatible,. You need a cast there. Other than that, +1 for ditching loops. – JNF Aug 21 '12 at 15:42
0

You can use GetFirstMonday(2010) for getting first Monday for Jan 2010. Or you can specify month also with GetFirstMonday(2010, 2) to get first Monday for Feb 2010.

GetFirstDayOfMonth can get any first day for given month, need to pass DayOfWeek value for to get result of required day.

// Common function to get first day for any month & year.
public DateTime GetFirstDayOfMonth(int year, int month, int day)
{        
    return new DateTime(year, month, 1)
           .AddDays((7 - datetime.DayOfWeek.GetHashCode() + day) % 7);
}
public DateTime GetFirstMonday(int year, int month = 1)
{        
    return GetFirstDayOfMonth(year, month, DayOfWeek.Monday.GetHashCode());
}
Karan
  • 12,059
  • 3
  • 24
  • 40