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'");
To convert Python datetime to string, use the strftime() function. The strftime() method is a built-in Python method that returns the string representing date and time using date, time, or datetime object.
Get the date to be converted. Create an instance of SimpleDateFormat class to format the string representation of the date object. Get the date using the Calendar object. Convert the given date into a string using format() method.
The program below converts a datetime object containing current date and time to different string formats. Here, year , day , time and date_time are strings, whereas now is a datetime object.
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With