Last Sunday of the year in C #

How can I get the date of the last Sunday of the year in C #? Would gregoriancalendar class be useful?

+2


source to share


7 replies


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

Update: if the days of the week are numbered as follows:

0 Sun, 1 Mon, ... 6 Sat

      



then

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

      

+8


source


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

      

+7


source


I think you can use an integer enum representation DayOfWeek

for this:

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

      

+5


source


Since the DayOfWeek enumeration starts at 0 on Sunday, this should work:

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

      

+3


source


You can find out what day of the week is December 31st. Then (if not 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"));
}

      

+1


source


Sorry, but I don't have a C # version if you see here for a VB version. I suspect you can convert it.

0


source


It depends ... Do you want the last day of the year to be Sunday or Sunday of the last week of the year? Depending on how the weeks are defined in your country, the last week of a year can extend to six days the following year.

If you want to be the first, you can start on December 31st and go back until you find Sunday.

If you want the second, you will need to use the method System.Globalizartion.Calendar.GetWeekOfYear

to find out where the first week of the next year starts and take the day before.

0


source







All Articles