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


当前回答

试试这个尺寸:

您希望格式化的实际dateTime对象在dt中。Value属性,而不是dt2对象本身。

DateTime? dt2 = DateTime.Now;
 Console.WriteLine(dt2.HasValue ? dt2.Value.ToString("yyyy-MM-dd hh:mm:ss") : "[N/A]");

其他回答

简单的通用扩展

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

试试这个尺寸:

您希望格式化的实际dateTime对象在dt中。Value属性,而不是dt2对象本身。

DateTime? dt2 = DateTime.Now;
 Console.WriteLine(dt2.HasValue ? dt2.Value.ToString("yyyy-MM-dd hh:mm:ss") : "[N/A]");
Console.WriteLine(dt2 != null ? dt2.Value.ToString("yyyy-MM-dd hh:mm:ss") : "n/a"); 

编辑:如其他注释中所述,检查是否有一个非空值。

更新:如评论中推荐,扩展方法:

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

从c# 6开始,您可以使用空条件操作符来进一步简化代码。如果DateTime?是零。

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

你可以使用简单的线条:

dt2.ToString("d MMM yyyy") ?? ""

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

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