;

How to Get the Total Number of Mondays in the Month in C#


Tutorialsrack 01/03/2021 C#

In this article, you will learn how to get the total number of Mondays in the month in C#. In this program, the first step is to get the total number of days in the current month, and then find the first day. For each day in the month, check if the day is a Monday, if so, then increment the value. 

Program - How to Get the Total Number of Mondays in the Month in C#
using System;

namespace Tutorialsrack
{
    class Program
    {
        /* How to Get Total Number of Mondays in Month in C# */
        static void Main(string[] args)
        {

            Console.Write($"Total No. of Mondays in {DateTime.Now.Year}, {DateTime.Now.Month} Month: {MondaysInMonth(DateTime.Now)}");
            //Hit ENTER to exit the program
            Console.ReadKey();
        }
        
        public static int MondaysInMonth(DateTime thisMonth)
        {
            int totalMondays = 0;
            int month = thisMonth.Month;
            int year = thisMonth.Year;
            int daysThisMonth = DateTime.DaysInMonth(year, month);
            DateTime beginingOfThisMonth = new DateTime(year, month, 1);
            for (int i = 0; i < daysThisMonth; i++)
                if (beginingOfThisMonth.AddDays(i).DayOfWeek == DayOfWeek.Monday)
                    totalMondays++;
            return totalMondays;
        }
    }
}
Output

Total No. of Mondays in 2021, 3 Month: 5

I hope this article will help you to understand how to get the total number of Mondays in the month in C#.

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!


Related Posts



Comments

Recent Posts
Tags