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

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

    Here is Blake's excellent answer as an extension method. Add this to your project and the calls in the question will work as expected.
    Meaning it is used like MyNullableDateTime.ToString("dd/MM/yyyy"), with the same output as MyDateTime.ToString("dd/MM/yyyy"), except that the value will be "N/A" if the DateTime is null.

    public static string ToString(this DateTime? date, string format)
    {
        return date != null ? date.Value.ToString(format) : "N/A";
    }
    

提交回复
热议问题