Hii, Is there any way to find out the date in which last sunday of October in ASP.NET c# I am using .net 2.0
There is no need to run a loop for this:
private static DateTime GetLastWeekdayOfMonth(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);
}
This can easily be converted into an extension method, like so:
public static class DateTimeExtensions
{
public static DateTime GetLastWeekdayOfMonth(this 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);
}
}
...and can then be used directly from any DateTime object:
DayOfWeek lastSunday = DateTime.Now.GetLastWeekdayOfMonth(DayOfWeek.Sunday);
Update: fixed a bug.
You can try something like this
DateTime date = new DateTime(2009, 10, 01);
date = date.AddMonths(1).AddDays(-1);
while (date.DayOfWeek != DayOfWeek.Sunday) date = date.AddDays(-1);
or also try
date = date.AddDays(-(int)date.DayOfWeek);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With