开发者

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

开发者 https://www.devze.com 2023-04-03 14:27 出处:网络
Is there any easy way to check to see if the time part of the DateTime value is NULL other than checkin开发者_StackOverflow社区g hour is 0, min is 0 and sec is 0?

Is there any easy way to check to see if the time part of the DateTime value is NULL other than checkin开发者_StackOverflow社区g hour is 0, min is 0 and sec is 0?

Thanks.


I find this very readable:

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.


DateTime does not support the concept of null for just the time component. Either the whole DateTime object is null (if using the nullable version), or both the date and time are non-null. If you don't specify the time component it will default to 0 (midnight).


To avoid divisions and floating point accuracy issues use:

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

精彩评论

暂无评论...
验证码 换一张
取 消