abhi
abhi

Reputation: 3136

How do you handle NULLs in a Date field through your C# code?

I am currently setting the date field to a Datetime.Now which is being done through the SQL query on the database.

I do a

SELECT NVL(mydatefield, sysdate) FROM myView;

This is not the most elegant approach I can think of. The better practice would be to check for a NULL. I found that the DateTime class does not support the syntax that I am using for int values.

What approaches have you seen being used? What's your preference? How can you make a DateTime handle null values? I don't want the DateTime.ParseExact in my front-end code to throw an exception.

Upvotes: 3

Views: 338

Answers (1)

Brad
Brad

Reputation: 15577

DateTime? is a nullable DateTime. You could also use default(DateTime) to find non-set DateTime fields. A final option is to use DateTime.Min or DateTime.Max as a special value.

Instead of DateTime.ParseExact you can use DateTime.TryParse.

string input = "2010-10-04";
DateTime result;
bool success = DateTime.TryParse(input, out result);

Upvotes: 9

Related Questions