Jibu P Cherian
Jibu P Cherian

Reputation: 73

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

Upvotes: 7

Views: 7478

Answers (4)

Johnsen
Johnsen

Reputation: 1

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

Upvotes: -2

Fredrik Mörk
Fredrik Mörk

Reputation: 158319

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.

Upvotes: 23

moribvndvs
moribvndvs

Reputation: 42497

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.

Upvotes: 0

Adriaan Stander
Adriaan Stander

Reputation: 166416

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

Upvotes: 2

Related Questions