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

前端 未结 20 2374
面向向阳花
面向向阳花 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:26

    Console.WriteLine(dt2 != null ? dt2.Value.ToString("yyyy-MM-dd hh:mm:ss") : "n/a"); 
    

    EDIT: As stated in other comments, check that there is a non-null value.

    Update: as recommended in the comments, extension method:

    public static string ToString(this DateTime? dt, string format)
        => dt == null ? "n/a" : ((DateTime)dt).ToString(format);
    

    And starting in C# 6, you can use the null-conditional operator to simplify the code even more. The expression below will return null if the DateTime? is null.

    dt2?.ToString("yyyy-MM-dd hh:mm:ss")
    

提交回复
热议问题