views:

78

answers:

1

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.

+9  A: 

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);
Brad
Datetime? does not work in the same way as int?
abhi
@abhi, in my experience it works just fine. I use it all the time. Is there a specific example you can give?
Brad
I'm curious about an example as well @abhi...
Austin Salonen
default(DateTime) == DateTime.MinValue
Oded
@Austin / Brad,I have separated the chaff from the wheat, but here's something that I was trying to work with. string s; DateTime dt = new DateTime(); s = dt ? DateTime.Now.ToString(): "EMPTY";
abhi
@abhi, your condition here of simply `dt` is not a valid condition. How about `s = dt == null ? DateTime.Now.ToString() : "EMPTY";` Also, depending on speed and timing, this statement may still never evaluate to true (I realize you are probably just making an example).
Brad