Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set an empty DateTime variable

Tags:

c#

sql

datetime

I would declare an empty String variable like this:

    string myString = string.Empty; 

Is there an equivalent for a 'DateTime' variable ?

Update :

The problem is I use this 'DateTime' as a parameter for a 'StoredProcedure' in SQL. E.g:

    DateTime? someDate = null;     myCommand.Parameters.AddWithValue("@SurgeryDate", someDate); 

When I run this code an exception is catched telling me the 'StoredProcedure' expected a '@SurgeryDate' parameter. But i provided it. Any idea why?

like image 542
phadaphunk Avatar asked Apr 02 '12 19:04

phadaphunk


People also ask

How do I set empty DateTime?

DateTime. MinValue; The above will display the minimum value i.e. Let us see how to display the minimum value and avoid adding null to a date to initialize it as empty.

Can DateTime be null?

DateTime CAN be compared to null; It cannot hold null value, thus the comparison will always be false. DateTime is a "Value Type". Basically a "value type" can't set to NULL. But by making them to "Nullable" type, We can set to null.

How do I assign a null value to a DateTime variable in C#?

The Nullable < T > structure is using a value type as a nullable type. By default DateTime is not nullable because it is a Value Type, using the nullable operator introduced in C# 2, you can achieve this. Using a question mark (?) after the type or using the generic style Nullable.

How do you check if a DateTime field is not null or empty?

Use model. myDate. HasValue. It will return true if date is not null otherwise false.


1 Answers

Since DateTime is a value type you cannot assign null to it, but exactly for these cases (absence of a value) Nullable<T> was introduced - use a nullable DateTime instead:

DateTime? myTime = null; 
like image 191
BrokenGlass Avatar answered Sep 19 '22 01:09

BrokenGlass