richiee_chen
richiee_chen

Reputation: 1

Find Number of Days in one year using DateTime

I want to use DateTime to find the number of Saturdays and Sundays between the start of the input year and End of the input year using C# windows form.

Condition: I cannot use any loops to run through the start to the end of the year. I need to find a way to hard calculate the number of Saturdays and Sundays in one year.

The following is a code I wrote for the same goal using for loop for your reference:

 private void button1_Click(object sender, EventArgs e)
        {
            int inputYear = Convert.ToInt32(textBox1.Text);
            DateTime begginingOfYear = new DateTime(inputYear, 01, 01);
            DateTime endOfYear = new DateTime(inputYear + 1, 01, 01);


            int satIndex = 0;
            int sunIndex = 0;

            for (DateTime date = begginingOfYear; date <= endOfYear; date = date.AddDays(1))
            {
                if (date.DayOfWeek == DayOfWeek.Sunday)
                {
                    sunIndex++;
                }
                else if (date.DayOfWeek == DayOfWeek.Saturday)
                {
                    satIndex++;
                }
            }

            MessageBox.Show($"Saturdays{Convert.ToString(satIndex)}days , Sundays{Convert.ToString(sunIndex)}days");

Upvotes: 0

Views: 177

Answers (1)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

A year has 52 weeks plus 1 or 2 extra days, that's why given a year y

// int.TryParse can be a safier approach
int y = Convert.ToInt32(textBox1.Text);

we can use a simple condition:

int satIndex = new DateTime(y, 1, 1).DayOfWeek == DayOfWeek.Saturday ||
               new DateTime(y, 1, 1).DayOfWeek == DayOfWeek.Friday && 
                   DateTime.IsLeapYear(y)
  ? 53
  : 52;

int sunIndex = new DateTime(y, 1, 1).DayOfWeek == DayOfWeek.Sunday ||
               new DateTime(y, 1, 1).DayOfWeek == DayOfWeek.Saturday &&
                   DateTime.IsLeapYear(y)
  ? 53
  : 52;

Upvotes: 1

Related Questions