更新时间:2023-10-14 20:29:40
Console.WriteLine dt2!= null?dt2.Value.ToString(yyyy-MM-dd hh:mm:ss):n / a);
编辑:如其他注释中所述,检查是否存在非空值。 >
How can I convert the nullable DateTime dt2 to a formatted string?
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:
no overload to method ToString takes one argument
Console.WriteLine(dt2 != null ? dt2.Value.ToString("yyyy-MM-dd hh:mm:ss") : "n/a");
EDIT: As stated in other comments, check that there is a non-null value.