null 許容の 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 メソッドのオーバーロードは 1 つの引数を取りません
ベストアンサー1
Console.WriteLine(dt2 != null ? dt2.Value.ToString("yyyy-MM-dd hh:mm:ss") : "n/a");
編集: 他のコメントに記載されているように、null 以外の値があることを確認してください。
更新: コメントで推奨されているように、拡張メソッド:
public static string ToString(this DateTime? dt, string format)
=> dt == null ? "n/a" : ((DateTime)dt).ToString(format);
C# 6 以降では、null 条件演算子を使用してコードをさらに簡素化できます。以下の式は、がDateTime?
null の場合に null を返します。
dt2?.ToString("yyyy-MM-dd hh:mm:ss")