开发者

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

i want to pass in a year and get a date back that represents the first monday of the first开发者_C百科 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


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);
}


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());
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜