如何将可空的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方法没有重载 一个参数


当前回答

我认为你必须使用getvalueordefault - method。如果实例为空,则不定义ToString("yy…")的行为。

dt2.GetValueOrDefault().ToString("yyy...");

其他回答

c# 6.0宝贝:

dt2 ? . ToString(“dd / MM / yyyy”);

简单的通用扩展

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;
    }
}

考虑到您实际上想要提供格式,我建议将IFormattable接口添加到Smalls扩展方法中,这样您就不会有讨厌的字符串格式连接。

public static string ToString<T>(this T? variable, string format, string nullValue = null)
where T: struct, IFormattable
{
  return (variable.HasValue) 
         ? variable.Value.ToString(format, null) 
         : nullValue;          //variable was null so return this value instead   
}

您可以使用dt2. value . tostring ("format"),但当然这需要dt2 != null,这首先就否定了可空类型的使用。

这里有几个解决方案,但最大的问题是:您希望如何格式化空日期?

剃须刀的语法:

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