如何输出今年所有星期一的日期?

时间:2017-09-19 19:03:26

标签: c# date datetime while-loop dayofweek

我正在尝试输出今年所有星期一的日期,但我的if元素不适用于我提供的条件。

这是我的代码:

static void Main(string[] args)
{
    var dagEtt = new DateTime(DateTime.Now.Year, 1, 1);
    while (dagEtt <= DateTime.MaxValue)
    {
        if (dagEtt == DayOfWeek.Monday)
            Console.WriteLine(dagEtt);
        dagEtt = dagEtt.AddDays(1);
    }
}

2 个答案:

答案 0 :(得分:1)

我稍微更改了你的代码

var start = new DateTime(DateTime.UtcNow.Year, 1, 1);
var end = start.AddYears(1);

while (start < end)
{
    if (start.DayOfWeek == DayOfWeek.Monday)
    {
        Console.WriteLine(start);
        start = start.AddDays(7);
    }
    else
    start = start.AddDays(1);
}

答案 1 :(得分:0)

您可以使用%运算符计算一年中的第一个星期一。这大大简化了你的循环。

static void Main(string[] args)
{
    int year = DateTime.Now.Year;
    DateTime startDate = FirstMonday(year);

    while (startDate.Year == year)
    {
        Console.WriteLine(startDate);
        startDate = startDate.AddDays(7);
    }
}

https://stackoverflow.com/a/5665161/3194005

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

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