Find the date Last sunday of October in ASP.NET c#

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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.

Method 2

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);

Method 3

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());

I left it open ended so you could swap out the month with a parameter pretty easily.

Method 4

Sorry

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

is WRONG!

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x