从Nullable TimeSpan中获取Am/PM值
本文关键字:PM Am 获取 Nullable TimeSpan | 更新日期: 2023-09-27 18:09:02
我从数据库收到的时间作为类TimeSpan。为了显示为Am/PM,我将其切换为DateTime
@string.Format("{0:hh:mm:ss tt}", new DateTime().Add(t.BegTime))
这工作。
一旦我改变TimeSpan允许null,它停止工作。为什么?我该如何解决这个问题?
Try…
@string.Format("{0:hh:mm:ss tt}", new DateTime().Add(t.BegTime.HasValue ? t.BegTime.Value : new TimeSpan(0, 0, 0)));
这个答案还假设t.BegTime是一个可空的TimeSpan
试试这个…
@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,此代码将失败。你仍然有责任用一个警卫语句来检查这种可能性。