Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

asp.net

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

like image 960
Jibu P Cherian Avatar asked Nov 25 '09 07:11

Jibu P Cherian


2 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 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.

like image 180
Fredrik Mörk Avatar answered Sep 25 '22 01:09

Fredrik Mörk


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);
like image 24
Adriaan Stander Avatar answered Sep 24 '22 01:09

Adriaan Stander