Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 458
Hendra Avatar asked Jan 27 '14 06:01

Hendra


People also ask

What is UTC Format date time?

Description. UTC() takes comma-delimited date and time parameters and returns the number of milliseconds between January 1, 1970, 00:00:00, universal time and the specified date and time. Years between 0 and 99 are converted to a year in the 20th century (1900 + year) . For example, 95 is converted to the year 1995 .

Does DateTime default to UTC?

The time zone setting is stored in the TimeZone property of each datetime array. When you create a datetime, it is unzoned by default.

How do you use DateTime UTC?

The ToUniversalTime method converts a DateTime value from local time to UTC. To convert the time in a non-local time zone to UTC, use the TimeZoneInfo. ConvertTimeToUtc(DateTime, TimeZoneInfo) method. To convert a time whose offset from UTC is known, use the ToUniversalTime method.


1 Answers

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

like image 115
Matt Johnson-Pint Avatar answered Sep 28 '22 12:09

Matt Johnson-Pint