如何将可空的DateTime dt2转换为格式化的字符串?

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:

ToString方法没有重载 一个参数


当前回答

像这样简单的事情怎么样:

String.Format("{0:dd/MM/yyyy}", d2)

其他回答

简单的通用扩展

public static class Extensions
{

    /// <summary>
    /// Generic method for format nullable values
    /// </summary>
    /// <returns>Formated value or defaultValue</returns>
    public static string ToString<T>(this Nullable<T> nullable, string format, string defaultValue = null) where T : struct
    {
        if (nullable.HasValue)
        {
            return String.Format("{0:" + format + "}", nullable.Value);
        }

        return defaultValue;
    }
}

甚至在c# 6.0中有一个更好的解决方案:

DateTime? birthdate;

birthdate?.ToString("dd/MM/yyyy");

也许这是一个迟来的答案,但可能对其他人有所帮助。

简单的是:

nullabledatevariable.Value.Date.ToString("d")

或者用其他格式代替d。

Best

这个问题的问题在于,当可为空的datetime没有值时,您没有指定所需的输出。下面的代码将输出DateTime。MinValue在这种情况下,与当前接受的答案不同,将不会抛出异常。

dt2.GetValueOrDefault().ToString(format);

剃须刀的语法:

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