C#-在Int中获取Nullable DateTime的日期差 [英] C# - Get date difference of Nullable DateTime in int

查看:71
本文介绍了C#-在Int中获取Nullable DateTime的日期差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个可空类型的DateTime变量。

I have two DateTime variables of Nullable types.

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

我需要在int变量中获得这两个日期的差。我试过的是-

I need to get the difference of these two dates in an int variable. What I have tried is -

int daysBetweenDate = (date2 - date1).GetValueOrDefault().TotalDays;

但是我无法解决问题。


请注意,只有当两个值不为null时,才计算这两个日期的差。

It is taken care that the difference of these two dates will be calculated only if their values aren't null.


推荐答案

我会这样写:

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

所以 daysBetweenDate null ,如果 date1 date2 中的至少一个是

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

这篇关于C#-在Int中获取Nullable DateTime的日期差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆