Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to determine if a System.DateTime is midnight?

Tags:

.net

It seems that there are several possible ways to determine if a given System.DateTime represents midnight. What are the pros and cons of each? Is one more readable or perform better than the others?

EDIT: I believe that readability is more important than performance until profiling shows that there is an issue. That is why I asked about both.

Example 1

Public Function IsMidnight(ByVal value As Date) As Boolean     Return value.TimeOfDay = TimeSpan.FromHours(0) End Function 

Example 2

Public Function IsMidnight(ByVal value As Date) As Boolean     Return value.CompareTo(value.[Date]) = 0 End Function 
like image 352
Eric Weilnau Avatar asked Mar 25 '09 12:03

Eric Weilnau


People also ask

What is System DateTime?

The DateTime value type represents dates and times with values ranging from 00:00:00 (midnight), January 1, 0001 Anno Domini (Common Era) through 11:59:59 P.M., December 31, 9999 A.D. (C.E.) in the Gregorian calendar. Time values are measured in 100-nanosecond units called ticks.

What does DateTime now return in c#?

The Now property returns a DateTime value that represents the current date and time on the local computer.

What is Timeofday?

A time interval that represents the fraction of the day that has elapsed since midnight.


1 Answers

I'd check (using C# for the example):

bool isMidnight = value.TimeOfDay.Ticks == 0; 

IMO, this is easier than using FromHours etc, and doesn't involve any extra multiplication (since Ticks defined the TimeSpan - all the other properties are calculated).

like image 76
Marc Gravell Avatar answered Nov 08 '22 05:11

Marc Gravell