In C#, if you declare a DateTime type variable, it can only accept a valid date, time value. If they are invalid dates, it will not accept it. But what about if a date is simply null? Well it it wont take a null date either. So where is the solution?
I had similar situation where I had to format my datetime field which was actually stored in a string. I needed to output in proper date form in Excel Cell. When I would output it as string, it was not formatted properly and could not be formatted in Excel without clicking inside every cell. When I outputted as DateTime, it would throw exception on null dates. So I spend a couple of hours to find the solution. I was working on this logic
DateTime.TryParse(MyStringDate,out Date1) ? Date1 : null
but this did not work because null values can not be assigned to DateTime field.
First I noticed that there are nullable Datetime Field.
Nullable Datetime Type
This is declared as
Note that it is declare same as DateTime except that it has a question mark at the end. For more information please see nullabe types in C#. DateTime? (nullable) can basically store a valid datetime or a null value. Being nullable, it can also be check for true or false value as well.
The problem here I faced was you can not use TryParse with nullable DateTime field.
Use Shorthand If Else
Then I came across stackoverflow where Jon Skeet helped answer my problem by using the following syntax
DateTime.TryParse(MyStringDate,out Date1) ? Date1 : (DateTime?) null
This is the same syntax as I was working before but could not make it work now is workable. If string is correcly parsed as valid date, we return Date1 field or if it failed then we return null value but we must typecast it as nullable datetime in order for it to be accepted.
This solution worked in my problem where I just need to change the formatting of the output. The orginal string need not be changed.