5

可能重复:
如何使用 ToString() 格式化可为空的 DateTime?

解析日期时间有问题吗?为特定格式。喜欢:

 DateTime t1 = ...;
 string st1 = t1.ToString(format); //<-- works

 DateTime? t1 = ...;
 string st1 = t1.ToString(format); //Dont work.

DateTime 没有重载方法?

4

4 回答 4

12
if (t1.HasValue)
    string st1 = t1.Value.ToString(format);
于 2012-05-15T12:24:19.797 回答
3

使用合并运算符

DateTime? t1 = ...;

string st1 = t1 ?? t1.Value.ToString(format);
于 2012-05-15T12:25:37.000 回答
1

你可以这样尝试,nullabale 类型有一个叫做 hasValue 的属性 Nullable 有 Value

if (t1.HasValue)
   t1.Value.ToString(yourFormat)
于 2012-05-15T12:24:46.977 回答
0

您应该首先检查 DateTime 是否为空

 string strDate = (st1 != null ? st1.Value.ToString(format) : "n/a");
于 2012-05-15T12:26:25.537 回答