Click here to Skip to main content
15,884,898 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
How do I get the last monday of the month please?
Thanks
Posted

Have a look here: DateTime extensions to make some simple tasks a little more readable[^] - it includes last-x-of month.
 
Share this answer
 
Comments
Mehdi Gholam 6-Jun-12 4:26am    
Just posted the same, 5'ed
VJ Reddy 6-Jun-12 5:19am    
Good answer. 5!
VJ Reddy 6-Jun-12 12:14pm    
I have gone through the above Tip.

public static DateTime LastOfMonth(this DateTime dt, DayOfWeek dayOfWeek)
method works fine when the sought dayOfWeek enumeration value is less than or equal to the lastDayOfMonth.DayOfWeek enumeration value.

But is not working properly when the sought dayOfWeek enumeration value is more than the lastDayOfMonth.DayOfWeek enumeration value.
eg. DateTime date = new DateTime(2012,7,1);
var lastDay = date.LastOfMonth(DayOfWeek.Wednesday);
returned 7/30/2012 instead of 7/25/2012

I think
AddDays(lastDayOfMonth.DayOfWeek < dayOfWeek ?
dayOfWeek - lastDayOfMonth.DayOfWeek - 7 :
dayOfWeek - lastDayOfMonth.DayOfWeek)


can be used instead of

AddDays(Math.Abs(dayOfWeek - lastDayOfMonth.DayOfWeek) * -1)
in the above method.

Thank you.
OriginalGriff 6-Jun-12 12:43pm    
Oops! Sorry for that - fixed, credited and article re-submitted.
IOU 5!
VJ Reddy 6-Jun-12 12:53pm    
Thank you very much for the consideration :)
Try this:
C#
public static DateTime LastMonday(int year, int month)
{
    DateTime dt;
    if (month < 12)
        dt = new DateTime(year, month + 1, 1);
    else
        dt = new DateTime(year + 1, 1, 1);
    dt = dt.AddDays(-1);
    while (dt.DayOfWeek != DayOfWeek.Monday) dt = dt.AddDays(-1);
    return dt;
}
 
Share this answer
 
Comments
VJ Reddy 6-Jun-12 5:17am    
Good answer. 5!
Mehdi Gholam 6-Jun-12 5:36am    
Thanks VJ!
arkiboys 6-Jun-12 9:48am    
Thanks
Maciej Los 6-Jun-12 17:50pm    
Good answer, my 5!
Mehdi Gholam 7-Jun-12 1:35am    
Thanks losmac!
The following code can be used to get the LastDayOfMonth
C#
void Main()
{
    DateTime date = LastDayOfMonth(2012, 6, DayOfWeek.Monday);
    
    //date = 6/25/2012
}
    
public DateTime LastDayOfMonth(int year, int month, DayOfWeek dayOfWeek){
    DateTime lastDateOfMonth = new DateTime(year, month,
                                 DateTime.DaysInMonth(year,month));
    return lastDateOfMonth.AddDays(lastDateOfMonth.DayOfWeek < dayOfWeek ? 
    			dayOfWeek - lastDateOfMonth.DayOfWeek -  7 : 
    			dayOfWeek - lastDateOfMonth.DayOfWeek);
}
 
Share this answer
 
Comments
Maciej Los 6-Jun-12 17:50pm    
Good work, my 5!
VJ Reddy 6-Jun-12 19:37pm    
Thank you, losmac :)
Mehdi Gholam 7-Jun-12 1:35am    
5'ed
VJ Reddy 7-Jun-12 2:18am    
Thank you, Mehdi :)

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