在Getter / Setter属性中存储Utc时间

时间:2015-06-15 21:40:33

标签: c# asp.net datetime

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

我的代码:

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),
 });

2 个答案:

答案 0 :(得分:4)

要使DateTime存储UTC值,您必须为其分配UTC值。请注意使用DateTime.UtcNow代替DateTime.Now

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

DateTime.UtcNow documentation说:

  

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

DateTime.Now documentation说:

  

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

您可能希望改用DateTimeOffset。它总是毫不含糊地存储绝对时间点。

答案 1 :(得分:0)

您可以向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,您可以在其中设置属性的值。