将 UTC 时间存储在 getter/setter 属性中

本文关键字:setter 属性 getter UTC 时间 存储 | 更新日期: 2023-09-27 17:56:17

目前,我正在使用DeliveryDate getter/setter存储DateTime。但是,我在以 UTC 时间存储它时遇到问题。我已经对此进行了一些研究并尝试了DateTimeKind.Utc但无法使其正常工作。如何让DeliveryDate以 UTC 时间存储日期时间?

我的代码:

public partial class shippingInfo
{
    public System.Guid EmailConfirmationId {get; set; }
    public Nullable<System.DateTime> DeliveryDate {get; set; }
}

更新:添加了实现:

 DeliveryExpirationRepository.Add(new DeliveryPendingConfirmation
 {
     EmailConfirmationId = newGuid,
     DeliveryDate = DateTime.Now.AddHours(48),
 });

将 UTC 时间存储在 getter/setter 属性中

若要使DateTime存储 UTC 值,必须为其分配 UTC 值。请注意使用 DateTime.UtcNow 而不是 DateTime.Now

DeliveryExpirationRepository.Add(new DeliveryPendingConfirmation
{
    EmailConfirmationId = newGuid,
    DeliveryDate = DateTime.UtcNow.AddHours(48),
});

DateTime.UtcNow文档说:

获取一个DateTime对象,该对象在此计算机上设置为当前日期和时间,表示为协调世界时 (UTC)。

DateTime.Now文档说:

获取一个DateTime对象,该对象在此计算机上设置为当前日期和时间,表示为本地时间。

您可能希望改用DateTimeOffset。它始终明确地存储绝对时间点。

您可以向 setter 方法添加代码以检查值是否不在 UTC 中,并将此值转换为 UTC:

public class shippingInfo {
    public System.Guid EmailConfirmationId { get; set; }
    private Nullable<System.DateTime> fDeliveryDate;
    public Nullable<System.DateTime> DeliveryDate {
        get { return fDeliveryDate; }
        set {
            if (value.HasValue && value.Value.Kind != DateTimeKind.Utc) {
                fDeliveryDate = value.Value.ToUniversalTime();
            }
            else {
                fDeliveryDate = value;
            }
        }
    }
}

在这种情况下,您无需关心如何设置此属性的值。或者,可以使用 DateTime.ToUniversalTime 方法将任何日期转换为 UTC,在其中设置属性的值。