How can someone handle the default date and time in .Net

I have a DAL where I convert the null values ​​of a database to their equivalent representation in C #. For instance:

NULL for Numeric = 0 NULL for String = String.Empty NULL for DateTime = "1/1/0001" (ie DateTime.MinValue) 

The problem, by date, lies in the presentation layer, especially in GridViews. You cannot show 1/1/01 users.

What I did was check if myDate.Year=1 or myDate.Year < AcceptedDate and display an empty string, but this seems to be an extra effort, unlike other types

Please open for a better approach. Thanks.

+4
source share
6 answers

Use the Nullable data type to store a null value.

 DateTime? value = null; int? myNullableInt = 1; value = DateTime.Now; 

How to check if a value is null

 if (value!=null) 

A String value can hold a NULL value, so there is no different data type for a string to hold a null value.

 string var; if (var == null) 

or

 if (String.IsnullorEmpty(var)) 
+8
source

You can also use the constant DateTime.MinValue.

http://msdn.microsoft.com/en-us/library/system.datetime.minvalue.aspx

Your conditions:

 if (myDate == DateTime.MinValue) 
+6
source

You can use Nullable DateTime , so you will return DateTime? instead of DateTime from its DAL. This way you can check if the return value is null.

 DateTime? dateTime = null; 
+1
source

As others mention, you can use System::Nullable<DateTime> .

Another approach I've seen is to use a standard DateTime and just use a special value like DateTime.MinValue . This is useful if you need to respect existing interface types and cannot change DateTime to Nullable<DateTime> .

+1
source

You can use Nullable DateTime, like others, or use this trick: (To prevent invalid default values.)

 // If dateTime has not been initialize, initialize to Now // (or to any other legal inital values) dateTime = ((dateTime != new DateTime()) ? dateTime : DateTime.Now); 

This trick is useful if you need to use an invalid DateTime and want to provide a default value if it is missing. (For example, you have a DateTime column that does not contain NULL in DB and you want to set the value only if the row is new.)

+1
source

I don’t think you have much choice but to check like you and display accordingly. A type with a null value can simplify your work. Depending on your data, even numerical data should be handled this way. DBNull! = 0.

+1
source

Source: https://habr.com/ru/post/1416574/


All Articles