-1

As title, how should I get each Saturdays and Sundays in a given year like 2022, and also show the date of each Saturdays and Sundays? For example: The 1st Saturday is 2022/1/1. The 2nd Saturday is 2022/1/8 ... etc.

To be honest, I'm still the beginner of C#. There are few similar questions in this website; However, they all used class to solve the questions. Is it possible solving the question merely through for-loop, if statement or C# built-in functions (e.g. .AddDays(i) ...)?

Please help me with this. Thanks a million.

1 Answers1

1

You can do something like this.

void Main()
{
    var dates = GetWeekendDates(new DateTime(2022,1,1), new DateTime(2022,12,31));
}

// You can define other methods, fields, classes and namespaces here

static public List<string> GetWeekendDates(DateTime startDate, DateTime endDate)
{
    List<string> weekendList = new List<string>();
    for (DateTime date = startDate; date <= endDate; date = date.AddDays(1))
    {
        if (date.DayOfWeek == DayOfWeek.Sunday || date.DayOfWeek == DayOfWeek.Saturday)
            weekendList.Add(date.ToShortDateString());
    }

    return weekendList;
}

This will return 105 dates that are weekends.

enter image description here

If you don't want string and want the datetimes just change method to this:

public static List<DateTime> GetWeekendDates(DateTime startDate, DateTime endDate)
{
    List<DateTime> weekendList = new List<DateTime>();
    for (DateTime date = startDate; date <= endDate; date = date.AddDays(1))
    {
        if (date.DayOfWeek == DayOfWeek.Sunday || date.DayOfWeek == DayOfWeek.Saturday)
            weekendList.Add(date);
    }

    return weekendList;
}
mathis1337
  • 1,426
  • 8
  • 13