简体   繁体   中英

Convert DateTime? to string

I want to convert a DateTime? to string. If a date is null then return "" , else return a string format like this: "2020-03-05T07:52:59.665Z" . The code is something like this but it won't work. It said "DateTime?" do not contain a definition for "ToUniversalTime". Someone know how to fix this?

DateTime? date = DateTime.UtcNow;

var dateInUTCString = date == null ? "" : date.ToUniversalTime().ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'");

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'") ?? "";

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 technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM