从 Nullable TimeSpan 获取 Am/PM 值
Get Am/PM value from Nullable TimeSpan
我正在从数据库中获取时间 class TimeSpan。为了显示为 Am/PM 我将其切换为 DateTime
@string.Format("{0:hh:mm:ss tt}", new DateTime().Add(t.BegTime))
这有效。
一旦我更改了 TimeSpan 以允许 Nulls,它就停止工作了。为什么?我该如何解决这个问题?
试试这个...
@string.Format("{0:hh:mm:ss tt}", new DateTime().Add(t.BegTime.Value))
可空类型有 "Value" 属性。有关详细信息,请参阅 https://msdn.microsoft.com/en-us/library/ydkbatt6(v=vs.110).aspx。
编辑:正如 Igor 所指出的,如果 BegTime 为 Null,则此代码将失败。你仍然有责任用保护语句包装它以检查这种可能性。
尝试...
@string.Format("{0:hh:mm:ss tt}", new DateTime().Add(t.BegTime.HasValue ? t.BegTime.Value : new TimeSpan(0, 0, 0)));
这个答案还假设 t.BegTime 是一个 Nullable TimeSpan
我正在从数据库中获取时间 class TimeSpan。为了显示为 Am/PM 我将其切换为 DateTime
@string.Format("{0:hh:mm:ss tt}", new DateTime().Add(t.BegTime))
这有效。
一旦我更改了 TimeSpan 以允许 Nulls,它就停止工作了。为什么?我该如何解决这个问题?
试试这个...
@string.Format("{0:hh:mm:ss tt}", new DateTime().Add(t.BegTime.Value))
可空类型有 "Value" 属性。有关详细信息,请参阅 https://msdn.microsoft.com/en-us/library/ydkbatt6(v=vs.110).aspx。
编辑:正如 Igor 所指出的,如果 BegTime 为 Null,则此代码将失败。你仍然有责任用保护语句包装它以检查这种可能性。
尝试...
@string.Format("{0:hh:mm:ss tt}", new DateTime().Add(t.BegTime.HasValue ? t.BegTime.Value : new TimeSpan(0, 0, 0)));
这个答案还假设 t.BegTime 是一个 Nullable TimeSpan