Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check for default DateTime value?

I need to check a DateTime value if it has a value or not.

I have several options:

if (dateTime == default(DateTime)) 

or

if (dateTime == DateTime.MinValue) 

or using a nullable DateTime?

if (nullableDateTime.HasValue) 

Personally I would prefer the third version, since its pretty good readable. But in our database we have some datetime columns which are defined as not null. So in some cases I have to go with the first two options.

I read somewhere that the default keyword should be used when working with generics, but isn't it much more readable in this case? When using the second option I have to know that the default value of a new and empty DateTime instance is DateTime.MinValue which has the smell of an implementation detail for me.

So which option should I use to use "best practice"?

like image 331
dasheddot Avatar asked Apr 29 '13 14:04

dasheddot


People also ask

What is the default value for DateTime?

The default and the lowest value of a DateTime object is January 1, 0001 00:00:00 (midnight).

How do I find the default date in SQL Server?

SYSDATETIME() will get the current date and time. Make sure the data type of the column is datetime , and not just date or it won't be able to hold a datetime. Show activity on this post. Most SQL implementations (engines) do have CURRENT_TIMESTAMP function.

How do I check if a nullable DateTime is null?

If you are using DateTime then DateTime dat = new DateTime();if (dat==DateTime. MinValue){//unassigned datetime}Or if you are using nullable DateTime then DateTime? dat = null;if (!

What is the value of DateTime MinValue?

The value of this constant is equivalent to 00:00:00.0000000 UTC, January 1, 0001, in the Gregorian calendar. MinValue defines the date and time that is assigned to an uninitialized DateTime variable.


2 Answers

I would probably make this really explicit:

// Or private, or maybe even public internal static readonly DateTime MagicValueForNullDateTimeInNonNullableColumns     = DateTime.MinValue; 

Okay, so I'd make the name slightly less wordy, but you get what I mean. It doesn't really matter much how you initialize that value - it's clear what you're trying to do.

(Of course, use a nullable type any time you can for this. I'm assuming the question was asked because you couldn't do so in certain situations.)

like image 66
Jon Skeet Avatar answered Oct 07 '22 00:10

Jon Skeet


I need to check a DateTime value if it has a value or not.

You've pretty-much described the textbook situation requiring a Nullable<DateTime>. I'd go with that option.

(You'd obviously need some sort of translation layer if you need to persist the values to a non-null db column, but I'd try to keep any "magic" value as close to the db as possible, and try to keep your C# code clean and idiomatic.)

like image 42
LukeH Avatar answered Oct 06 '22 22:10

LukeH