How to subtract a year from the datetime?

C#

C# Problem Overview


How to subtract a year from current datetime using c#?

C# Solutions


Solution 1 - C#

var myDate = DateTime.Now;
var newDate = myDate.AddYears(-1);

Solution 2 - C#

DateTime oneYearAgoToday = DateTime.Now.AddYears(-1);

Subtracting a week:

DateTime weekago = DateTime.Now.AddDays(-7);

Solution 3 - C#

It might be worth noting that the accepted answer may adjust the date by either 365 days or 366 days due to leap years (it gets the date for the same day of the month one year ago, with the exception of 29th February where it returns 28th February).

In the vast majority of cases this is exactly what you want however if you are treating a year as a fixed unit of time (e.g. the Julian year) then you would need to subtract from either days;

        var oneFullJulianYearAgo = DateTime.Now.AddDays(-365.25);

or seconds;

        var oneFullJulianYearAgo = DateTime.Now.AddSeconds(-31557600);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJangoView Question on Stackoverflow
Solution 1 - C#D'Arcy RittichView Answer on Stackoverflow
Solution 2 - C#kemiller2002View Answer on Stackoverflow
Solution 3 - C#mark_hView Answer on Stackoverflow