Convert DateTime? to string
While you can use the Value
property directly as per Leszek's answer, I'd probably use the null-conditional operator in conjunction with the null-coalescing operator:
string dateInUTCString =
date?.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ", CultureInfo.InvariantCulture)
?? "";
Here the ?.
will just result in a null value if date
is null, and the ??
operator will provide a default value if the result of the date?.ToUniversalTime().ToString(...)
call is null (which would only happen if date
is null).
Note that you really want to specify the invariant culture to avoid getting unexpected results when the current thread's culture doesn't use the Gregorian calendar, and you don't need to quote all those literals in the format string. It certainly works when you do so, but it's harder to read IMO.
If you don't mind how much precision is expressed in the string, you can make the code simpler using the "O" standard format string:
string dateInUTCString = date?.ToUniversalTime().ToString("O") ?? "";
At that point you don't need to specify CultureInfo.InvariantCulture
as that's always used by "O".
The DateTime?
have the Value
property and the HasValue
property
Try:
var dateInUTCString = date.HasValue ? date.Value.ToUniversalTime().ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'") : "";
You can use a short version:
var dateInUTCString = date?.ToUniversalTime().ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'") ?? "";