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.
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;
}
}
}
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!
Comments