How can I format a nullable DateTime with ToString()?

Viewed 211799

How can I convert the nullable DateTime dt2 to a formatted string?

DateTime dt = DateTime.Now;
Console.WriteLine(dt.ToString("yyyy-MM-dd hh:mm:ss")); //works

DateTime? dt2 = DateTime.Now;
Console.WriteLine(dt2.ToString("yyyy-MM-dd hh:mm:ss")); //gives following error:

no overload to method ToString takes one argument

21 Answers

RAZOR syntax:

@(myNullableDateTime?.ToString("yyyy-MM-dd") ?? String.Empty)

s.DateTime != null ? ((DateTime)s.SendDateTime).ToString("HH:mm:ss") : null

Related