Get the number of weeks in a month C#

 How can I get the number of weeks in a month using C# (dot net core)?


Considering Sunday as the first day of the week.


using System;
using System.Collections.Generic;
using System.Linq;


public static int GetTotalWeeksInMonth(DateTime dt)
//extract the month
int daysInMonth = DateTime.DaysInMonth(dt.Year, dt.Month);
DateTime firstOfMonth = new DateTime(dt.Year, dt.Month, 1);
//days of week starts by default as Sunday = 0
int firstDayOfMonth = (int)firstOfMonth.DayOfWeek;
int weeksInMonth = (int)Math.Ceiling((firstDayOfMonth + daysInMonth) / 7.0);
return weeksInMonth;


Ask a Question


Email *

Message *

Popular posts from this blog

Get current week number from Date C#

All git commands you need — get rid of merge conflicts