Question

How can I get date of last sunday of a year in C#?? Will gregoriancalendar class be of help?

Was it helpful?

Solution

I don't know if there is a method for that but a simple way is to check the last 7 days of December, starting from 31st day and counting down.

Update: actually if the days of week are numbered like this:

0 Sun, 1 Mon, ... 6 Sat

then

lastSunday = 31 - DayOfWeek(31, 12, 2009) // pseudocode

OTHER TIPS

Not the nicest solution but should work:

int year = 2009;
DateTime lastSunday = new DateTime(year, 12, 31);
while (lastSunday.DayOfWeek != DayOfWeek.Sunday)
{
    lastSunday = lastSunday.AddDays(-1);
}

I think you can use the integer representation of the DayOfWeek enumeration for this:

DateTime endOfYear = new DateTime(DateTime.Now.Year, 12, 31);
DateTime lastSunday = endOfYear.AddDays(-(int)endOfYear.DayOfWeek);

As the enumeration of DayOfWeek starts at 0 for Sunday, this should work:

    int Year = 2009;
    DateTime endOfYear = new DateTime(Year, 12, 31);
    DateTime sunday = endOfYear.AddDays(-(int)endOfYear.DayOfWeek); 

You can find out what day of the week december 31 is. Then (if not a sunday) calculate back ...

for (int y=2009; y<=2018; y++)
{
  DateTime dt = new DateTime(y, 12, 31); // last day of year
  dt = dt.AddDays(-(int)dt.DayOfweek); // sun == 0, so then no change
  Console.WriteLine(dt.ToString("dddd dd-MM-yyyy"));
}

Sorry but I don't have a C# version be if you see here for VB version. I suspect you'll be able to convert it.

That depends... Do you want the last day of the year that is a sunday, or the sunday of the last week of the year? Depending on how weeks are determined in your country, the last week of the year may go up to six days into the next year.

If you want the first, you can just start at the 31st of december and go back until you find a sunday.

If you want the second, you will have to use the System.Globalizartion.Calendar.GetWeekOfYear method to find out where the first week of the next year starts, and take the day before that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top