How to get the date of last Sunday in a month using asp.net with c#

protected void Page_Load(object sender, EventArgs e)
{
DateTime currentDateTime=System.DateTime.Now;
Response.Write(GetLastWeekdayInMonth(System.DateTime.Now, DayOfWeek.Sunday));

}
private static DateTime GetLastWeekdayInMonth(DateTime date, DayOfWeek day)
{
DateTime lastDayOfMonth = new DateTime(date.Year, date.Month, 1)
.AddMonths(1).AddDays(-1);
int wantedDay = (int)day;
int lastDay = (int)lastDayOfMonth.DayOfWeek;
return lastDayOfMonth.AddDays(
lastDay >= wantedDay ? wantedDay - lastDay : wantedDay - lastDay - 7);
}
Output
5/29/2011 12:00:00 AM

So this the way to get the date of last sunday in a month/get the date of last week day using asp.net with c#.

0 comments:

Post a Comment