16

I have a requirement to store all of the dates recorded in database must be recorded as UTC. So far I can achieve this using Noda library with following method:

    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.

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.

4

2 に答える 2

40

ご質問の内容がよくわかりませんが、ヒントをいくつかご紹介します。

  • UTC として「今」だけが必要な場合はDateTime、 を使用してDateTime.UtcNowください。

  • Noda Time インスタントを使用していて が必要な場合はDateTime、 を使用してinstant.ToDateTimeUtc()ください。UTC だけが必要な場合は、タイム ゾーンを操作しても意味がありません。

  • a が UTC であることを検証する場合DateTimeは、種類を確認します。

    dateTime.Kind == DateTimeKind.Utc
    
  • データ層はおそらくDateTimeKind.Unspecifiedの種類を返すDateTimeので、最初に UTC の種類を指定してから Noda Time に変換する必要がありますInstant

    DateTime dt = (DateTime) dataReader["YourDataField"];
    DateTime utc = DateTime.SpecifyKind(dt, DateTimeKind.Utc);
    Instant instant = Instant.FromDateTimeUtc(utc);
    
  • 最後に、UTC はformatではないことを認識してください。タイムスケールです。したがって、値を「UTC に調整」または「UTC の種類」にすることはできますが、「UTC 形式」にすることはできません。

于 2014-01-27T16:58:25.593 に答える