Problem: Initially, we have programmed a block of code to be executed once every month on the first week of Monday. But due to some process dependency, now, the code could be executed on the first, second, third or fourth week of the month.
Solution: Created a Utilities class with method that accepts the DayOfWeek and week number parameters. Below is the implementation and explanation.
public static DateTime DayInWeekNumber(DayOfWeek theDay, int weekNumber)
{
DateTime dtFirstDateOfMonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1); //get the first date of the month
DateTime dtResult = new DateTime();
//Sunday=0, Monday =1, Tuesday = 2, Wednesday =3, Thursday = 4, Friday=5, Saturday=6
//day of the first day of the week
int intDayOfWeek = (int)dtFirstDateOfMonth.DayOfWeek;
//day of the theDay
int intFirstDayOfWeek = (int)theDay;
//initialize variables
int intFirstDay = intFirstDayOfWeek;
int numDays = 0;
//get the first day of a given dayofweek
intFirstDay = dtFirstDateOfMonth.AddDays((7 - intDayOfWeek + intFirstDayOfWeek) % 7).Day;
//the day of a given week number
numDays = (7 * (weekNumber - 1) + intFirstDay);
//to ensure the day is within the month range
if (DaysInMonth() >= numDays)
{
return dtResult = DateTime.Parse(dtFirstDateOfMonth.Month + "/" + numDays + "/" + dtFirstDateOfMonth.Year);
}
else
{
return dtResult; //return 01/01/0001
}
}
//overload method that accept three parameters, same explanation as above
public static DateTime DayInWeekNumber(DayOfWeek theDay, int weekNumber, DateTime dtSpecify)
{
DateTime dtFirstDateOfMonth = new DateTime(dtSpecify.Year, dtSpecify.Month, 1); //first date of the month
DateTime dtResult = new DateTime();
int intDayOfWeek = (int)dtFirstDateOfMonth.DayOfWeek;
int intFirstDayOfWeek = (int)theDay;
int intFirstDay = intFirstDayOfWeek;
int numDays = 0;
intFirstDay = dtFirstDateOfMonth.AddDays((7 - intDayOfWeek + intFirstDayOfWeek) % 7).Day;
numDays = (7 * (weekNumber - 1) + intFirstDay);
if (DaysInMonth() >= numDays)
{
return dtResult = DateTime.Parse(dtFirstDateOfMonth.Month + "/" + numDays + "/" + dtFirstDateOfMonth.Year);
}
else
{
return dtResult; //return 01/01/0001
}
}
///
/// return the number of days in current year and month
///
///
public static int DaysInMonth()
{
return System.DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);
}
How to use it.
//get the date for Wednesday for week number four from the current month and year
DateTime dayInWeek = DayInWeekNumber(DayOfWeek.Wednesday, 4);
if (dayInWeek.Day == DateTime.Now.Day)
{
Response.Write("Do something here");
}
//get the date for Tuesday for week number three in Jan 2009
DateTime dt = DayInWeekNumber(DayOfWeek.Tuesday, 3, DateTime.Parse("01/01/2009"));
Comments are welcome. Happy coding!