-5

I'm trying to output the dates of all Mondays this year, but my if element won't work with the conditions I'm giving it.

This is my code:

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);
    }
}
Labbis
  • 19

2 Answers2

1

I changed your code a little bit

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);
}
tym32167
  • 4,741
  • 2
  • 28
  • 32
0

You can calculate the first Monday of the year using the % operator. This greatly simplifies your loop.

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);
}
Derrick Moeller
  • 4,808
  • 2
  • 22
  • 48