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


当前回答

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

简单的是:

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

或者用其他格式代替d。

Best

其他回答

考虑到您实际上想要提供格式,我建议将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   
}

c# 6.0宝贝:

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

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

DateTime? birthdate;

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

下面是Blake作为一种扩展方法给出的优秀答案。将此添加到项目中,问题中的调用将按预期工作。 这意味着它的使用类似MyNullableDateTime.ToString("dd/MM/yyyy"),输出与MyDateTime.ToString("dd/MM/yyyy")相同,只是如果DateTime为空,则该值将为"N/A"。

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

这里有一个更通用的方法。这将允许您对任何可空值类型进行字符串格式化。我包含了第二个方法,允许重写默认字符串值,而不是为值类型使用默认值。

public static class ExtensionMethods
{
    public static string ToString<T>(this Nullable<T> nullable, string format) where T : struct
    {
        return String.Format("{0:" + format + "}", nullable.GetValueOrDefault());
    }

    public static string ToString<T>(this Nullable<T> nullable, string format, string defaultValue) where T : struct
    {
        if (nullable.HasValue) {
            return String.Format("{0:" + format + "}", nullable.Value);
        }

        return defaultValue;
    }
}