C#: how do I subtract two dates?

后端 未结 11 803
死守一世寂寞
死守一世寂寞 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条回答
  •  萌比男神i
    2020-12-19 07:15

    Well the point is that if you think of it, subtracting a date to another should not yield a date, it should yield a time span. And that is what happens when you use DateTime.Subtract().

    TimeSpan timeSpan = datenow - date1; //timespan between `datenow` and `date1`
    

    This will make your current code work.

    If on the other hand you want to subtract, let's say, one year from your date, you can use:

    DateTime oneYearBefore = DateTime.Now.AddYears(-1); //that is, subtracts one year
    

提交回复
热议问题