简体   繁体   English

如何在C#中找到两个DateTime之间的正差异

[英]How to find the positive difference between two DateTime in C#

I've two DateTime variable regardless of which is greater than the other in time. 我有两个DateTime变量,无论哪个变量大于另一个变量。

Datetime date1, date2;

How should I find the positive difference of both on "days" basis? 我怎样才能在“天”的基础上找到两者的积极差异?

(date1-date2) might give positive/negative result but I also need the no: of days difference. (date1-date2)可能会给出正面/负面结果,但我还需要no:of days difference。

Assume both are on the same TimeZone 假设两者都在同一个TimeZone上

double days = Math.Abs((date1-date2).TotalDays);

If you want an (unsigned) integer value: 如果你想要一个(无符号)整数值:

Math.Abs(date1.Subtract(date2).Days)

If you want an (unsigned) double value: 如果你想要一个(无符号)双精度值:

Math.Abs(date1.Subtract(date2).TotalDays)

Just use the Days property on the timespan (which is the resulting type from date1 - date2 ). 只需在时间跨度上使用Days属性(这是date1 - date2的结果类型)。 It returns a signed int. 它返回一个signed int。

You could try: 你可以尝试:

Math.Abs((dateA - dateB).Days);

or if you want the result to be fractional: 或者如果您希望结果是小数的:

Math.Abs((dateA - dateB).TotalDays);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM