In this article, we will learn how to get a week number of the month using a specific date in C#.
In .NET Framework, a DateTime class has no property or method or function to get a week number of the month using a specific date. So we are going to use this trick to get the week number of the month using a specific date.
using System;
namespace Tutorialsrack
{
class Program
{
/*How to get the Week number of the month using a specific date in C#*/
static void Main(string[] args)
{
//initialize a datetime variable with today
DateTime date = DateTime.Now;
//print Week No. of the Month
Console.WriteLine("Week Number of The Month is: {0}", GetWeekNumberOfMonth(date));
Console.ReadKey();
}
//This method is used to Get Week no. of the month
private static int GetWeekNumberOfMonth(DateTime date)
{
date = date.Date;
DateTime firstMonthDay = new DateTime(date.Year, date.Month, 1);
DateTime firstMonthMonday = firstMonthDay.AddDays((DayOfWeek.Monday + 7 - firstMonthDay.DayOfWeek) % 7);
if (firstMonthMonday > date)
{
firstMonthDay = firstMonthDay.AddMonths(-1);
firstMonthMonday = firstMonthDay.AddDays((DayOfWeek.Monday + 7 - firstMonthDay.DayOfWeek) % 7);
}
return (date - firstMonthMonday).Days / 7 + 1;
}
}
}
I hope this article will help you to understand how to get a week number of the month using a specific date in C#.
Share your valuable feedback, please post your comment at the bottom of this article. Thank you!
Comments