Question

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.

Était-ce utile?

La solution

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.

  • If you are working with Noda Time instants and need a DateTime, just use instant.ToDateTimeUtc(). There's no point in working with time zones if you just need UTC.

  • If you want to validate a DateTime is in UTC, then check the kind:

    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:

    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. 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".

Autres conseils

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

DateTimeOffset localServerTime = DateTimeOffset.Now;

DateTimeOffset utc = localServerTime.ToUniversalTime();

Console.WriteLine("UTC:{0}", utc);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top