简体   繁体   English

C#DateTime - 如何检查时间部分是否为空?

[英]C# DateTime - How to check Time part is NULL?

Is there any easy way to check to see if the time part of the DateTime value is NULL other than checking hour is 0, min is 0 and sec is 0? 是否有任何简单的方法来检查DateTime值的时间部分是否为NULL,而不是检查小时是0,min是0还是秒是0?

Thanks. 谢谢。

我觉得这很可读:

var isTimeNull = (myDateTime.TimeOfDay == TimeSpan.Zero);

Here are my takes: 这是我的需要:

var isTimeNull = myDateTime.Date == myDateTime;
var isTimeNull = myDateTime.TimeOfDay.TotalSeconds == 0;

And technically, time is not null, it's just not set. 从技术上讲,时间不是空的,它只是没有设置。

为避免划分和浮点精度问题,请使用:

var isMidnight = myDateTime.TimeOfDay.Ticks == 0;

DateTime does not support the concept of null for just the time component. DateTime不支持时间组件的null概念。 Either the whole DateTime object is null (if using the nullable version), or both the date and time are non-null. 整个DateTime对象为null(如果使用可空版本),或者日期和时间都为非null。 If you don't specify the time component it will default to 0 (midnight). 如果未指定时间组件,则默认为0(午夜)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM