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)?
Solution:
Considering Sunday as the first day of the week.
Imports:
using System;
using System.Collections.Generic;
using System.Linq;
Method:
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;
}
Comments
Post a Comment