Persisting DateTimeOffset to server

10,502

A few things:

  • +04:00 is an offset used in parts of Russia, and a few places in the Middle-East. From the location mentioned on your blog, I think you meant -04:00, which is used for Eastern Daylight Time in the US (among others). (The JavaScript getTimezoneOffset method is inverted with this regard.)

  • + ':00' assumes that all time zone offsets are in terms of whole hours. In reality, many are :30 and a few are :45.

  • In a DateTimeOffset, the DateTime portion is always the local time, not the UTC time. In other words, the offset is already applied.

    For example, if the local time is 2017-06-16 12:00:00 in the US Eastern time zone, then we'd represent that as 2017-06-16T12:00:00-04:00 (in ISO 8601 format). The corresponding UTC time would be represented as 2017-06-16T16:00:00Z.

  • Sending the UTC time plus the the local offset is not allowed in ISO 8601 format. The only format I'm aware of that uses that convention is the older "ASP.NET JSON Date Format", that came out of things like JavaScriptSerializer class in .NET. The corresponding value to the previous example would be /Date(1497628800000-0400)/. As you can see, the timestamp portion is a millisecond-resolution version of Unix Time, which is UTC based. The offset has not been applied, and is thus extraneous. This format considered deprecated now, so please don't do this.

  • You appear to be using moment.js on the client side. This can easily generate the string you need to send.

    // get the current time, as an ISO 8601 string, with whole-second resolution
    moment().format()  // "2017-06-16T12:00:00-04:00"
    
    // or, with millisecond resolution
    moment().format('YYYY-MM-DD[T]HH:mm:ss.SSSZ')  // "2017-06-16T12:00:00.000-04:00"
    
  • On the server side, just expose your property as a DateTimeOffset. Don't try to construct it yourself.

Share:
10,502
The Pax Bisonica
Author by

The Pax Bisonica

Updated on June 15, 2022

Comments

  • The Pax Bisonica
    The Pax Bisonica about 2 years

    I'm trying my best to figure out how to persist a datetimeoffset string to the server so that it correctly binds to a DateTimeOffset property.

    I've tried using something like this:

    moment.utc().format() + ' +' +  new Date().getTimezoneOffset() / 60 + ':00';
    

    This was showing as 6/12/2017 22:27 +4:00 and I was sending that to the server as a string but it seems to fail being parsed to a DateTimeOffset object every time.

    I'm using Nancy for my web api framework at the moment, but I wonder the same thing for Web API as well.

    Currently I'm just sending back the offset and setting the DateTimeOffset property like this:

    dto.CommentDate = new DateTimeOffset(DateTime.UtcNow).ToOffset(new TimeSpan(dto.Offset, 0, 0));

    Is there a better way to do this? Can I send the whole date instead of just the offset?