两个日期之间的差异 - 无法将类型 'int?' 转换为 'System.TimeSpan'

Difference between two dates - Cannot Convert type 'int?' to 'System.TimeSpan'

我试图计算两个日期之间的差异,但出现此错误:

Cannot Convert type 'int?' to 'System.TimeSpan'

然后我尝试使用Convert.ToInt32()Int32.Parse(),但仍然有同样的错误。 任何人都可以帮助我或指出正确的方向吗?

视图模型:

 public class RMACLOSE
 {
     public TimeSpan? diff { get; set; }
 }

控制器:

var list = from RH in RMA_History
select new RMACLOSE 
{
    // Cannot Convert type 'int?' to 'System.TimeSpan?'
    diff = DbFunctions.DiffDays(RH.EndDate, RH.StartDate) 
}

RH.EndDate (DateTime): 2018-11-15 12:15:00.000
RH.StartDate (DateTime): 2018-05-24 15:43:00.000

差异:175 天

从错误消息中可以看出,DbFunctions.DiffDays() returns 一个 int? (大概代表天数的时差)。

因此你需要做这样的事情把它转换成TimeSpan?:

var days = DbFunctions.DiffDays();

if (days != null)
    diff = TimeSpan.FromDays(days.Value);
else
    diff = null;

我认为您需要日期表示 EndDateStartDate 之间的区别,即 175

那么为什么你不能在 RMACLOSE class 中使用 int? 类型的 diff 属性 比如

public class RMACLOSE
{
    public int? diff { get; set; }
}

并且可能是您的错误得到解决,然后您不需要任何类型转换,您只需使用 LINQ 查询就可以了

select new RMACLOSE 
{    
  diff = DbFunctions.DiffDays(RH.EndDate, RH.StartDate)   
}

DbFunctions.DiffDays returns int? 所以它匹配你的 diff 属性 类型然后不会有错误。