Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert DateTime? to string

Tags:

c#

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'");
like image 531
KaMaHe Avatar asked Mar 05 '20 08:03

KaMaHe


People also ask

How do I convert datetime to string in Python?

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.

Can we convert date to string?

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.

Is datetime date a string?

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.


Video Answer


2 Answers

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'") ?? "";
like image 53
Leszek Mazur Avatar answered Oct 17 '22 23:10

Leszek Mazur


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".

like image 32
Jon Skeet Avatar answered Oct 17 '22 23:10

Jon Skeet