Find the last Sunday of each month: Difference between revisions

(Rewritten as now use of temporary invalid dates is forbidden.)
Line 796:
{
date = new DateTime(year, i, DateTime.DaysInMonth(year, i), System.Globalization.CultureInfo.CurrentCulture.Calendar);
/* Modification by Albert Zakhia on 2021-16-02
The below code is very slow due to the loop, we will go twice as fast
while (date.DayOfWeek != DayOfWeek.Sunday)
{
date = date.AddDays(-1);
}
*/
// The updated code
int daysOffest = date.DayOfWeek - dayOfWeek; // take the offset to subtract directly instead of looping
if (daysOffest < 0) daysOffest += 7; // if the code is negative, we need to normalize them
date = date.AddDays(-daysOffest); // now just add the days offset
Console.WriteLine(date.ToString("yyyy-MM-dd"));
}