Learn how to get the date of last sunday in a month using asp.net with c#

In this programming tutorial you will learn how to get the date of last sunday in a month using asp.net with c#. It is quite easy in asp.net. Let`s have a look over how to do so.

Getting the date of last sunday in a month using asp.net with c#

   protected void Page_Load(object sender, EventArgs e)
    {
 DateTime currentDateTime=System.DateTime.Now;
        Response.Write(GetLastWeekdayInMonth(System.DateTime.Now, DayOfWeek.Sunday));

    }
    private static DateTime GetLastWeekdayInMonth(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);
    }

Output
5/29/2011 12:00:00 AM

So this the way to get the date of last sunday in a month/get the date of last week day using asp.net with c#.

I hope you will find this tutorial very informative.

I love your feedback.

0 comments: