Subtracting two dates

守給你的承諾、 提交于 2019-11-30 04:43:51

You can use someDateTime.Subtract(otherDateTime), this returns a TimeSpan which has a TotalDays property.

Jon Skeet

Just use:

TimeSpan difference = end - start;
double days = difference.TotalDays;

Note that if you want to treat them as dates you should probably use

TimeSpan difference = end.Date - start.Date;
int days = (int) difference.TotalDays;

That way you won't get different results depending on the times.

(You can use the Subtract method instead of the - operator if you want, but personally I find it clearer to use the operator.)

Think about it.
How do you express a difference betwen two dates? With another date?
That's why you need the TimeSpan

DateTime dtToday = new System.DateTime(2012, 6, 2, 0, 0, 0);
DateTime dtMonthBefore = new System.DateTime(2012, 5, 2, 0, 0, 0);
TimeSpan diffResult = dtToday.Subtract(dtMonthBefore);
Console.WriteLine(diffResult.TotalDays);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!