C#: how do I subtract two dates?

后端 未结 11 819
死守一世寂寞
死守一世寂寞 2020-12-19 06:52

Here\'s my code:

DateTime date1 = new DateTime(byear, bmonth, bday, 0, 0, 0);
DateTime datenow =  DateTime.Now;
DateTime date2 = datenow - date1
11条回答
  •  太阳男子
    2020-12-19 07:21

    You are expecting the difference of two dates to be a date which is not. That being said, if you need to subtract a certain number of days or months, it can easily be done using the built in methods of the DateTime object such as .AddDays(-1), note that I used a negative number to substract, you can apply the opposite. Here is a quick example.

            DateTime now = DateTime.Now;
    
            // Get the date 7 days ago
            DateTime sevenDaysAgo = now.AddDays(-7);
    
            // Bulk: Get the date 7 days and two hours ago
            DateTime sevenDaysAndtwoHoursAgo = now.Add(-(new TimeSpan(7, 2, 0, 0)));
    

提交回复
热议问题