C# 两个日期相减

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10871755/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 15:37:14  来源:igfitidea点击:

Subtracting two dates

c#datetimecalendartimespan

提问by sd_dracula

I have two calendars and each return a DateTime from calendar.SelectedDate.

我有两个日历,每个都从 calendar.SelectedDate 返回一个 DateTime。

How do I go about subtracting the two selected dates from each other, giving me the amount of days between the two selections?

我如何将两个选定的日期相减,得到两个选择之间的天数?

There is a calendar.Subtract() but it needs a TimeSpan instead of DateTime.

有一个 calendar.Subtract() 但它需要一个 TimeSpan 而不是 DateTime。

采纳答案by C.Evenhuis

You can use someDateTime.Subtract(otherDateTime), this returns a TimeSpanwhich has a TotalDaysproperty.

您可以使用someDateTime.Subtract(otherDateTime),这将返回TimeSpan具有TotalDays属性的 。

回答by Jon Skeet

Just use:

只需使用:

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

Note that if you want to treat them as datesyou 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 Subtractmethod instead of the -operator if you want, but personally I find it clearer to use the operator.)

(如果需要,您可以使用该Subtract方法而不是-运算符,但我个人认为使用运算符更清晰。)

回答by Steve

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

想想看。
你如何表达两个日期之间的差异?和另一个约会?
这就是为什么你需要 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);