查找两个日期时间之间的总天数?变量

Find TotalDays between two Datetime? variables

   DateTime? arrival = (DateTime?)(t.ArrivalDate.Value);
   DateTime? departure = (DateTime?)(t.DepartureDate);

好的,我知道它们都可以为 null,并且 .TotalDays 不适用于可为 null 的对象。所以请告诉我我应该如何找到这两个对象之间的天数差异。

注意: 两个对象都包含日期,即不为空

Note: Both objects contains Date(s) i.e. are not null

如果您确定日期永远不会为空,那么您可以将 .Value 用于可为 null 的 DateTime 对象。当它们中的任何一个为空时,您将得到异常。

double days = departure.Value.Subtract(arrival.Value).TotalDays;

如果其中任何一个为空,它们之间的差异就没有有意义的价值,您只需要关心它们不为空的情况:

DateTime? arrival = (DateTime?)(t.ArrivalDate.Value);
DateTime? departure = (DateTime?)(t.DepartureDate);
double? totalDays = arrival.HasValue && departure.HasValue 
   ? (double?)(departure - arrival).GetValueOrDefault().TotalDays
   : null;

减法应该有效,因为隐式转换为 DateTime

    //Set dates
    DateTime? beginDate = DateTime.Now;
    DateTime? endDate = DateTime.Now.AddDays(10);

    //Check both values have a value (they will based on above)
    //If they do get the ticks between them
    long diff = 0;
    if (beginDate.HasValue && endDate.HasValue)
        diff = endDate.Value.Ticks - beginDate.Value.Ticks;

    //Get difference in ticks as a time span to get days between.
    int daysDifference =  new TimeSpan(diff).Days;

这里我给你测试过的代码请看:

 DateTime? startDate = DateTime.Now;
        DateTime? endDate = DateTime.Now.AddDays(5);


        long differenceOfDays = 0;
        if (startDate.HasValue && endDate.HasValue)
            differenceOfDays = endDate.Value.Ticks - startDate.Value.Ticks;

        int daysDifference = new TimeSpan(differenceOfDays).Days;