Find Date Last Sunday of October in ASP.NET C #

Hii, is there a way to find out the date of the last Sunday of October in ASP.NET C # I am using .net 2.0

+5
source share
4 answers

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 be easily converted to an extension method, for example:

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 then can be used directly from any DateTime object:

DayOfWeek lastSunday = DateTime.Now.GetLastWeekdayOfMonth(DayOfWeek.Sunday);

Update: Bug fixed.

+16
source

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 try

date = date.AddDays(-(int)date.DayOfWeek);
0
source
DateTime current = new DateTime(DateTime.Today.Year, 
    10, DateTime.DaysInMonth(DateTime.Today.Year, 10));

while (current.DayOfWeek != DayOfWeek.Sunday)
{
    current = current.AddDays(-1);
}

Console.WriteLine(current.ToLongDateString());

, .

0

DateTime lastDayOfMonth = new DateTime(date.Year, date.Month, 1)
        .AddMonths(1).AddDays(-1); 

!

=> DateTime lastDayOfMonth = new DateTime(aYear, aMonth, DateTime.DaysInMonth(aYear, aMonth));
-2

All Articles