简体   繁体   English

验证System.DateTime是UTC格式

[英]Validate System.DateTime is in a UTC format

I have a requirement to store all of the dates recorded in database must be recorded as UTC. 我要求存储数据库中记录的所有日期必须记录为UTC。 So far I can achieve this using Noda library with following method: 到目前为止,我可以使用Noda库使用以下方法实现此目的:

    public static DateTime NowUtc(string timeZoneId)
    {
        var timeZone = GetTimeZone(timeZoneId);
        var instant = SystemClock.Instance.Now;
        return instant.InZone(timeZone).ToDateTimeUtc();
    }

I'm going to validate every date that passed into data access layer must be in UTC format. 我将验证传递到数据访问层的每个日期必须是UTC格式。

How do I achieve that? 我如何实现这一目标?

Thanks 谢谢

Note: I have created a custom class library that used Noda as the core engine and the output is converted back to System.DateTime. 注意:我创建了一个自定义类库,它使用Noda作为核心引擎,输出转换回System.DateTime。

I'm not completely sure what you are asking, but here are some tips: 我不完全确定你在问什么,但这里有一些提示:

  • If all you need is "now" as a UTC DateTime , just use DateTime.UtcNow . 如果你需要的只是“now”作为UTC DateTime ,只需使用DateTime.UtcNow

  • If you are working with Noda Time instants and need a DateTime , just use instant.ToDateTimeUtc() . 如果您正在使用Noda Time时刻并需要DateTime ,请使用instant.ToDateTimeUtc() There's no point in working with time zones if you just need UTC. 如果您只需要UTC,那么使用时区是没有意义的。

  • If you want to validate a DateTime is in UTC, then check the kind: 如果要验证DateTime是否为UTC,请检查类型:

     dateTime.Kind == DateTimeKind.Utc 
  • Your data layer will probably return DateTimeKind.Unspecified kinds of DateTime , so you would need to first specify the UTC kind before converting to a Noda Time Instant : 您的数据层可能会返回DateTimeKind.Unspecified种类的DateTime ,因此您需要在转换为Noda Time Instant之前首先指定UTC类型:

     DateTime dt = (DateTime) dataReader["YourDataField"]; DateTime utc = DateTime.SpecifyKind(dt, DateTimeKind.Utc); Instant instant = Instant.FromDateTimeUtc(utc); 
  • Lastly, recognize that UTC isn't a format . 最后,要认识到UTC不是一种格式 It's a time scale. 这是一个时间尺度。 So a value can be "adjusted to UTC", or "of UTC kind", but it can't be "in UTC format". 因此,值可以“调整为UTC”或“UTC种类”,但不能是“UTC格式”。

Please go through http://msdn.microsoft.com/en-us/library/system.datetimeoffset.aspx 请浏览http://msdn.microsoft.com/en-us/library/system.datetimeoffset.aspx

DateTimeOffset localServerTime = DateTimeOffset.Now;

DateTimeOffset utc = localServerTime.ToUniversalTime();

Console.WriteLine("UTC:{0}", utc);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM