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

Okay i know both of them are nullable and .TotalDays does not work on nullable object. So kindly tell me how am i supposed to find days difference between these two objects.

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

4

4 回答 4

4

如果它们中的任何一个为空,则它们的差异没有有意义的价值,因此您只需要关注它们不存在的情况:

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

由于隐式转换为 ,减法应该起作用DateTime

于 2015-02-09T05:25:56.370 回答
1

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

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

double days = departure.Value.Subtract(arrival.Value).TotalDays;
于 2015-02-09T05:25:04.807 回答
0
    //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;
于 2015-02-09T06:16:17.150 回答
0

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

 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;
于 2015-02-09T06:56:53.693 回答