Here is the code that can do what you want - but test cases show that there are angular cases:
using System;
public class Test
{
static void Main()
{
Console.WriteLine(SameDayLastYear(DateTime.Today));
Console.WriteLine(SameDayLastYear(new DateTime(2010, 12, 31)));
}
static DateTime SameDayLastYear(DateTime original)
{
DateTime sameDate = original.AddYears(-1);
int daysDiff = original.DayOfWeek - sameDate.DayOfWeek;
return sameDate.AddDays(daysDiff);
}
}
What would you like to receive for the second call? This code is returned on January 1, 2010, because the nearest date is "a year ago on the same day."
I highly recommend that you have everything, you have unit tests that check leap years, the beginning and end of the year, etc.
source
share