How to subtract a year from the datetime?

后端 未结 3 1123
半阙折子戏
半阙折子戏 2020-12-09 14:14

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

相关标签:
3条回答
  • DateTime oneYearAgoToday = DateTime.Now.AddYears(-1);
    

    Subtracting a week:

    DateTime weekago = DateTime.Now.AddDays(-7);
    
    0 讨论(0)
  • 2020-12-09 14:52
    var myDate = DateTime.Now;
    var newDate = myDate.AddYears(-1);
    
    0 讨论(0)
  • 2020-12-09 14:58

    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);
    
    0 讨论(0)
提交回复
热议问题