计算两个日期之间的差返回负数 [英] Calculate difference between two dates returns a negative number

查看:379
本文介绍了计算两个日期之间的差返回负数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试计算不同日期之间有多少天。就像话题说的那样,我得到的是负面价值。我想我可以取绝对值,但是它返回负值的事实使我怀疑计算是否正确。下面是我的代码:

I am trying to calculate how many days there are between different dates. Like the topic says, I'm getting a negative value. I guess I could just take the absolute value, but the fact that it returns a negative value, makes me doubt if the calculations are correct. Below is my code:

DateTime previousDay = new DateTime(1998, 6, 31, new GregorianCalender());
DateTime nextDay = new DateTime(1998, 6, 3, new GregorianCalender());

TimeSpan differenceInDays = (nextDay - previousDay); 
double xAxisValue = differenceInDays.TotalDays;

当然,3-31给出-28,但是由于我们希望显示之间的天数,所以没有感觉它没有返回正值。我做错什么了吗?

Ofcourse 3-31 gives -28, but since we want it to show days between, it makes no sense that it doesn't return a positive value. Am I doing something wrong?

我也尝试过这种方法:

(a - b).TotalDays

其中a和b均为Datime类型

where a and b are of type Datime

推荐答案


我想我可以取绝对值,但是它返回负值的事实使我怀疑如果计算正确。

I guess I could just take the absolute value, but the fact that it returns a negative value, makes me doubt if the calculations are correct.

为什么? nextDay previousDay 早,因此当然要减去 previousDay 会给出否定的结果。

Why? nextDay is earlier than previousDay, so of course subtracting previousDay will give a negative result.

您实际上是在问:我需要添加多少天到 previousDay 为了到达 nextDay ?答案是-28。

You're effectively asking "How many days do I need to add to previousDay in order to get to nextDay? The answer is -28.

做什么担心我是这里的名字-我希望 nextDay 的值始终晚于 previousDay 的值-因此

What does concern me is the names here - I'd expect a nextDay value to always be later than a previousDay value - so either the way you're finding those values is incorrect, or you need to change the names to make the meaning clearer. Presumably they're not "next" and "previous" in respect to the same context.

这篇关于计算两个日期之间的差返回负数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆