可空的DateTime到String

Jes*_*aja 3 c# datetime

我想将Nullable DataTime转换为字符串.

DateTime datetime = DateTime.Now;
string strdatetime = datetime.ToString("MM/dd/yyyy");
Run Code Online (Sandbox Code Playgroud)

以上编码工作正常,不可为空的DateTime.

DateTime? datetime = DateTime.Now;
string strdatetime = datetime.ToString("MM/dd/yyyy");
Run Code Online (Sandbox Code Playgroud)

这个显示错误No overload for method 'ToString' takes 1 arguments.

小智 15

尝试这个,

 string strdatetime = datetime.HasValue ? datetime.Value.ToString("MM/dd/yyyy") : string.Empty;
Run Code Online (Sandbox Code Playgroud)