【问题标题】:whats the simplest way to calculate the Monday in the first week of the year计算一年中第一周星期一的最简单方法是什么
【发布时间】:2020-08-04 20:14:08
【问题描述】:

我想过去一年并得到一个代表第一周第一个星期一的日期

所以:

  • 如果在 2011 中通过,我会返回 2011 年 1 月 3 日
  • 如果在 2010 中通过,我会返回 2010 年 1 月 4 日

【问题讨论】:

标签: c# datetime


【解决方案1】:
private DateTime GetFirstMondayOfYear(int year)
{
    DateTime dt = new DateTime(year, 1, 1);

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

    return dt;
}

【讨论】:

  • 这是一年中的第一个星期一,这可能是 OP 想要的。但是请注意,ISO 对“第一周”有一个定义,根据该定义,N 年第一周的星期一实际上可能落在 N-1 年。
【解决方案2】:

试试这个没有循环的解决方案:

public DateTime FirstMonday(int year)
{
    DateTime firstDay = new DateTime(year, 1, 1);

    return new DateTime(year, 1, (8 - (int)firstDay.DayOfWeek) % 7 + 1);
}

【讨论】:

  • int & DayOfWeek 不兼容,。你需要一个演员在那里。除此之外,+1 表示放弃循环。
【解决方案3】:

您可以使用GetFirstMonday(2010) 获取Jan 2010 的第一个星期一。或者您也可以使用 GetFirstMonday(2010, 2) 指定月份,以获取 Feb 2010 的第一个星期一。

GetFirstDayOfMonth 可以获取给定月份的任何第一个day,需要传递DayOfWeek 值以获得所需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());
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多