C# 为什么Timespan减法返回错误值?

C# 为什么Timespan减法返回错误值?,c#,date,timespan,C#,Date,Timespan,我试图用一个时间跨度来找出两个日期之间的天数 nextdate1='2014-12-20' today `='2014-12-18'` 我的示例代码是: DateTime nexdate1 = dr.GetDateTime(2); //gets from database. I checked and the value is correct DateTime today = DateTime.Now; TimeSpan nextdate = nexdate1.Subtract(tod

我试图用一个时间跨度来找出两个日期之间的天数

nextdate1='2014-12-20'

today    `='2014-12-18'`
我的示例代码是:

DateTime nexdate1 = dr.GetDateTime(2); //gets from database. I checked and the value is correct
DateTime today = DateTime.Now;
TimeSpan nextdate = nexdate1.Subtract(today);
int difference = nextdate.Days;
现在我得到
difference=1
。实际上,
的差别是2(20-18)


为什么将差异显示为1?

TimeSpan.Days
是一个
int
。你的答案被截断了

在以下代码中:

var date1 = DateTime.Parse("Dec 12, 2014");
var date2 = DateTime.Parse("Dec 14, 2014");
var difference = (date2 - date1).Days;
差异
设置为2

但在这部法典中:

var date1 = DateTime.Parse("Dec 12, 2014 12:01 AM");
var date2 = DateTime.Parse("Dec 14, 2014");

var difference = (date2 - date1).Days;
差异
设置为1

当我们查看timespan
date2-date1
时,我们得到以下结果:

{1.23:59:00}
    Days: 1
    Hours: 23
    Minutes: 59
    Seconds: 0
    TotalDays: 1.9993055555555554

您应该设置
nextDate=nextdate1.Date.Subtract(DateTime.Today)
这样您就可以只查看天数的差异,或者取
(int)Math.Round(nextDate.TotalDays)

实际上您的datetime变量有时间部分,因为时间会影响结果。因此,您必须只查找datetime值的日期部分:

使用

这样做:

DateTime nexdate1 = dr.GetDateTime(2);
DateTime today = DateTime.Now;
TimeSpan nextdate = nexdate1.Date.Subtract(today.Date); // Here find only date part from datetime value.
//TimeSpan nextdate = nexdate1-today
int difference = nextdate.Days;

日期的“时间”部分是什么?比如说1天23小时吗?你是在从对方身上减去整个日期时间,而不仅仅是天数(注意,47小时之类的时间会给你一天)。试着使用dr.GetDateTime(2)。Date和DateTime.Now.Date,看看这是否有区别。时区??“减法(DATETIME)方法在执行减法时不考虑这两个DATETIME值的值属性。在减去DATETIME对象之前,请确保对象表示同一时区中的时间。否则,结果将包括时区之间的差异。”“发现这有用”——Aron,它只显示1,没有小时和部分all@SaraJohn如果建议的答案对你有用,请将其标记为答案!谢谢,描述得很好,喜欢吗