How to get the the week number of the first day of a given month and year C#
I am currently trying to get the week number of the first day of a given month and year in C#, but I didn't find any solution, HELP!
Example :
if I give it month :02 and year : 2021 it will return the week number of the first day of february which is : Week 05
If I give it month :01 and year : 2021 it will return the week number of the 1st day of January which is : Week 53
1 answer
-
answered 2021-02-19 13:50
Luke_
Ok so you have the year (lets say 1984) and you have a month (lets say june). The date we are interested in is therefore 1-6-1984. We can construct this date like this:
DateTime d = new DateTime(1984, 6, 1);
We also need to have a CultureInfo because the concept of "weeks" can differ all around the world
CultureInfo myCI = new CultureInfo("en-US"); Calender myCal = myCI.Calendar;
We can now see what day of the week this is by doing this:
int week = GetWeekOfYear(d, myCI.DateTimeFormat.CalendarWeekRule, myCI.DateTimeFormat.FirstDayOfWeek;);
Therefore we can make a method for this like this:
public int getDayOfWeekFromMonthAndYear(int month, int year) { DateTime d = new DateTime(1984, 6, 1); CultureInfo myCI = new CultureInfo("en-US"); int week = myCal.GetWeekOfYear(d, myCI.DateTimeFormat.CalendarWeekRule, myCI.DateTimeFormat.FirstDayOfWeek;); }