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

Waqar Ahmed
  • 203
  • 1
  • 4
  • 17

4 Answers4

4

Since there's no meaningful value to their difference if any of them is null, you only need to concern yourself with the case where they're not:

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

The subtraction should work because of implicit casting to DateTime.

Avner Shahar-Kashtan
  • 14,492
  • 3
  • 37
  • 63
1

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

If you are sure that dates never have null then you can use .Value for nullable DateTime objects. You will get exception when any of them is null.

double days = departure.Value.Subtract(arrival.Value).TotalDays;
Adil
  • 146,340
  • 25
  • 209
  • 204
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;
Noel
  • 567
  • 1
  • 4
  • 11
0

Here i give you tested code please have a look :

 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;
Aditya
  • 44
  • 1
  • 12