c# - 如何将可为空的 DateTime 转换为 UTC DateTime

标签 c# datetime model-view-controller nullable null-coalescing-operator

我正在读回日期时间?我认为的值(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.HasValuetrue , 左边不是 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/

相关文章:

c# - 在后台线程中监听事件

matlab - 如何在 MATLAB 中将日期时间设置为 5 的倍数?

javascript - 如何知道从所有选项中选择了哪个单选按钮?

c# - 隐藏在 c# 中的方法以及一个有效的例子。为什么在框架中实现?什么是现实世界的优势?

C# Regex.Replace,冒号作为分隔符,忽略日期时间格式

javascript - 如果从 2 个不同的时区运行 javascript "(new Date()).getTime()"

java - 登录用户 null Auth0/Spark Java

model-view-controller - MVC::什么是模型?

c# - 如何使用 CSV 文件中的数据运行 XUnit 测试

javascript - 日期类转换时间戳错误