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

前端 未结 20 2391
面向向阳花
面向向阳花 2020-11-27 12:04

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

DateTime dt = DateTime.Now;
Console.WriteLine(dt.ToString(\"yyyy-MM-dd hh         


        
20条回答
  •  难免孤独
    2020-11-27 12:38

    The problem with formulating an answer to this question is that you do not specify the desired output when the nullable datetime has no value. The following code will output DateTime.MinValue in such a case, and unlike the currently accepted answer, will not throw an exception.

    dt2.GetValueOrDefault().ToString(format);
    

提交回复
热议问题