views:

440

answers:

7

Hi guys,

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

+1  A: 

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"));
}
Hans Kesting
A: 

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.

Preet Sangha
+7  A: 

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
Nick D
+8  A: 

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);
}
Frank Bollack
nice work dude..............
Thomas Manalil
This works fine, but Fredrik's code (and Nick's pseudocode) are more concise and efficient.
LukeH
A: 

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.

Guffa
i need which date falls to the last sunday of a year.
Thomas Manalil
Yes, but what do you consider being the last sunday of the year? The last day of the year that is a sunday, or the sunday in the last week of the year? Also, is the sunday the first or last day of the week where you live?
Guffa
+4  A: 

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);
Fredrik Mörk
+2  A: 

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