Click here to Skip to main content
15,891,184 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
given the year as int i.e. 2012 and the month as text i.e. "january"
how do I find the last monday of the previous month?
Thanks
Posted

Something like this:

C#
FindDate(2012, "January", DayOfWeek.Monday);

C#
public static DateTime FindDate(int year, string month, DayOfWeek day)
       {
           DateTime lastDay = new DateTime(year, DateTime.ParseExact(month, "MMMM", CultureInfo.CurrentCulture).Month, 1).AddMonths(1).AddDays(-1);
           DayOfWeek lastDow = lastDay.DayOfWeek;
           int diff = day - lastDow;

           return lastDay.AddDays(diff).Date;
       }
 
Share this answer
 
Comments
Prasad_Kulkarni 13-Jun-12 5:18am    
5'ed!
arkiboys 13-Jun-12 5:33am    
thank you
VJ Reddy 13-Jun-12 8:20am    
The above code gives the date as 30/1/2012. I think the
.AddMonths(1).AddDays(-1); in the FindDate method is to be
.AddDays(-1);
If so then it returns 26/12/2011, which is correct.

It works fine when the required day of the week is before the DayOfWeek of the last day of month as in the above case. But, when the required day of week is after the day of week of the last day of month, then the correct date is not obtained
for eg. if we use
FindDate(2012, "February", DayOfWeek.Thursday);
it returns
2/2/2012 whereas the correct date is 26/1/2012

I have used another alternative.

Please see my solution.

Thank you.
Manas Bhardwaj 13-Jun-12 9:09am    
Thanks for pointing out!
VJ Reddy 13-Jun-12 12:55pm    
Thank you, Manas, for the response :)
The following code can be used to find required last day of the previous month
C#
void Main()
{
    DateTime date = LastDayOfPreviousMonth(2012, "January", DayOfWeek.Monday);
    Console.WriteLine (date);
    
    //date
    //26/12/2011
}
    
public DateTime LastDayOfPreviousMonth(int year, string month, DayOfWeek dayOfWeek){
    int monthNo = Array.IndexOf(System.Globalization.CultureInfo
			.InvariantCulture.DateTimeFormat.MonthNames, month)+1;
    DateTime lastDateOfPrevMonth = new DateTime(year, monthNo,1).AddDays(-1);
    							 
    return lastDateOfPrevMonth.AddDays(lastDateOfPrevMonth.DayOfWeek < dayOfWeek ? 
    			dayOfWeek - lastDateOfPrevMonth.DayOfWeek -  7 : 
    			dayOfWeek - lastDateOfPrevMonth.DayOfWeek);
}
 
Share this answer
 
v3
Comments
Prasad_Kulkarni 13-Jun-12 8:24am    
My 5!
VJ Reddy 13-Jun-12 8:28am    
Thank you, Prasad :)
Manas Bhardwaj 13-Jun-12 9:08am    
Correct +5!
VJ Reddy 13-Jun-12 12:55pm    
Thank you, Manas :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900