C#: how do I subtract two dates?

后端 未结 11 798
死守一世寂寞
死守一世寂寞 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:38

    You are correctly subtracting two dates in your code. What's going on is that you expect the difference between the two dates to be another date, and that's not the case.

    As other posters have noticed, you get a TimeSpan. From your variable names I get the sense you're trying to find out someone's age.

    Age is not a date, it's a duration. Read up on the TimeSpan object and you will find that it correctly expresses the idea you are looking for.

    I'm not 0029-01-01 years old, I'm 29 years old. (Today is not my birthday, but assume it is for easy math.)

    If you're trying to show someone's age in a control and that control wants a DateTime you are probably using the wrong control to do it.

提交回复
热议问题