Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Nullable<DateTime> to string

Tags:

c#

datetime

I have a DateTime? variable, sometimes the value is null, how can I return an empty string "" when the value is null or the DateTime value when not null?

like image 829
JL. Avatar asked Sep 18 '09 17:09

JL.


2 Answers

Though many of these answers are correct, all of them are needlessly complex. The result of calling ToString on a nullable DateTime is already an empty string if the value is logically null. Just call ToString on your value; it will do exactly what you want.

like image 136
Eric Lippert Avatar answered Oct 11 '22 21:10

Eric Lippert


string date = myVariable.HasValue ? myVariable.Value.ToString() : string.Empty;
like image 23
Jon Seigel Avatar answered Oct 11 '22 20:10

Jon Seigel