C# - Get date difference of Nullable DateTime in int

前端 未结 2 679
悲&欢浪女
悲&欢浪女 2021-01-29 03:23

I have two DateTime variables of Nullable types.

DateTime? date1 = new DateTime();
DateTime? date2 = new DateTime();

I need to get the differe

相关标签:
2条回答
  • 2021-01-29 03:39

    I would write something like:

    int? daysBetweenDate = date1.HasValue && date2.HasValue ? (int?)(date2.Value - date2.Value).TotalDays : null;
    

    So daysBetweenDate is null if at least one of date1 and date2 is null.

    0 讨论(0)
  • 2021-01-29 03:41

    If your goal is to return null when one (or both) of the dates is null, you can write like this (if you can use ? operator which is available in C# 6.0 compiler):

    int? days = (int?) (date1 - date2)?.TotalDays;
    
    0 讨论(0)
提交回复
热议问题