我正在读回日期时间?我认为的值(value)。现在我检查 NextUpdate
日期时间是否? HasValue
,如果是,则将该时间转换为 UTC
。
阅读这篇文章后,我似乎需要使用 null coalescing operator
但我的作业告诉我 System.NUllable 不包含 ToUniversalTime()
的定义使用该运算符时。
我在 SO 上搜索了一个类似的问题,但没有成功。
问题:
如何将空 DateTime 值转换为 UTC?
代码:
我只是检查 DateTime?有一个值,如果有,则将该 DateTie 转换为 UTC -
if (escalation.NextUpdate.HasValue)
{
escalation.NextUpdate = escalation.NextUpdate ?? escalation.NextUpdate.ToUniversalTime();
}
else
{
escalation.NextUpdate = null;
}
模型中我的 NextUpdate
属性:
public DateTime? NextUpdate { get; set; }
最佳答案
您的代码有不止一处错误。
??
如果不为空,则运算符返回左侧,否则返回右侧。
由于您已经检查过 escalation.NextUpdate.HasValue
是true
, 左边不是 null
然后您再次分配相同的日期(不转换为 UTC)。
Nullable<DateTime>
不声明ToUniversalTime()
,您需要对值执行此操作。
所以最终的代码应该是这样的:
if (escalation.NextUpdate.HasValue)
escalation.NextUpdate = escalation.NextUpdate.Value.ToUniversalTime();
或使用 C#6
escalation.NextUpdate = escalation.NextUpdate?.ToUniversalTime();
不需要 else
分支,因为在这种情况下它将是 null
无论如何。
关于c# - 如何将可为空的 DateTime 转换为 UTC DateTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37589303/