21

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?

Thanks.

4 Answers 4

27

I find this very readable:

var isTimeNull = (myDateTime.TimeOfDay == TimeSpan.Zero);
3
  • Thanks - is better than .ToString.Equals("00:00:00") :)
    – AjV Jsy
    Commented Dec 10, 2015 at 12:48
  • This checks if it is zero, which is a different concept to something being null
    – thelem
    Commented Mar 9, 2018 at 17:50
  • 1
    I believe this will fail if the time of day is precisely midnight. Commented Mar 16, 2021 at 22:02
15

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.

5
  • Thanks Anton and let me try this.
    – JKK
    Commented Sep 9, 2011 at 11:14
  • 9
    How's that different from it being midnight? Commented Sep 9, 2011 at 11:18
  • I went with myDateTime.TimeOfDay.TotalSeconds logic. In my case, I have 2 dates (start date and end date). Based on whether the time component is filled, I change Oracle to_date() function. It works like a charm in all cases except one case where the user is trying to search for records exactly at the midnight (12 AM) on both date values. Thanks Anton.
    – JKK
    Commented Sep 9, 2011 at 11:39
  • @DavidKemp: Do you have a solution for this?
    – testing
    Commented Feb 7, 2017 at 17:12
  • @testing maybe a different library, like Noda Time, that allows you to express dates and times as separate concepts - nodatime.org/1.3.x/userguide/core-types.html Commented Feb 8, 2017 at 9:36
3

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).

2

To avoid divisions and floating point accuracy issues use:

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.