Chrome interprets ISO time without Z as UTC; C# issue

后端 未结 5 2083
野性不改
野性不改 2020-12-11 02:23

Run this jsfiddle: http://jsfiddle.net/E9gq9/7/ on Chrome, FF, and IE and you get:

Chrome:

Chrome http://images.devs-on.net/Image/vBTz86J0f4o8zlL3-Region.png

相关标签:
5条回答
  • 2020-12-11 02:57

    At the end of the day, the problem I'm facing in this app can be fixed if my server always sends the client DateTime objects in a format that all browsers deal with correctly.

    This means there must be that 'Z' on the end. Turns out the ASP.NET MVC4 Json serializer is based on Json.NET, but does not have Utc turned on by default. The default for DateTimeZoneHandling appears to be RoundtripKind and this does not output the values with Z on them, even if DateTime.Kind == Utc, which is quite annoying.

    So the fix appears to be, set the way Json.NET handles timezones to DateTimeZoneHandling.Utc:

    var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
    // Force Utc formatting ('Z' at end). 
    json.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
    

    Now, everything coming down the wire from my server to the browser is formatted as ISO-8601 with a 'Z' at the end. And all browsers I've tested with do the right thing with this.

    0 讨论(0)
  • 2020-12-11 03:01

    Should we just append Z to them on the server side?

    TL;DR Yes, you probably should.

    Correct handling of dates and date/times without a timezone has, sadly, varied through the years — both in terms of specification and JavaScript engines adherence to the specification.

    When this answer was originally written in 2013, the ES5 spec (the first to have a defined date/time format for JavaScript) was clear: No timezone = UTC:

    The value of an absent time zone offset is “Z”.

    This was at odds with ISO-8601, which the ES5 date/time format was based on, in which the absense of a timezone indicator means "local time." Some implementations never implemented ES5's meaning, sticking instead to ISO-8601.

    In ES2015 (aka "ES6"), it was changed to match ISO-8601:

    If the time zone offset is absent, the date-time is interpreted as a local time.

    However, this caused incompatibility problems with existing code, particularly with date-only forms like 2018-07-01, so in ES2016 it was changed yet again:

    When the time zone offset is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as a local time.

    So new Date("2018-07-01") is parsed as UTC, but new Date("2018-07-01T00") is parsed as local time.

    It's been consistent since, in ES2017 and in the upcoming ES2018; here's the link to the current draft standard, which also has the text above.

    You can test your current browser here:

    function test(val, expect) {
      var result = +val === +expect ? "Good" : "ERROR";
      console.log(val.toISOString(), expect.toISOString(), result);
    }
    test(new Date("2018-07-01"), new Date(Date.UTC(2018, 6, 1)));
    test(new Date("2018-07-01T00:00:00"), new Date(2018, 6, 1));

    Status as of April 2018:

    • IE11 gets it right (interestingly)
    • Firefox gets it right
    • Chrome 65 (desktop, Android) gets it right
    • Chrome 64 (iOS v11.3) gets the date/time form wrong (parses as UTC)
    • iOS Safari in v11.3 gets the date/time form wrong (parses as UTC)

    Oddly, I can't find an issue in the v8 issues list that's been fixed between v6.4 (the v8 in Chrome 64) and v6.5 (the v8 in Chrome 65); I can only find this issue which is still open, but which appears to have been fixed.

    0 讨论(0)
  • 2020-12-11 03:01

    David Hammond's answer is great but doesn't play all the tricks; so here is a modified version:

    • allows for fractional part in date/time string
    • allows for optional seconds in date/time string
    • considers crossing over daylight-saving time
    appendTimezone = function (/*String*/ d) {
        // check for ISO 8601 date-time string (seconds and fractional part are optional)
        if (d.search(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d{1-3})?)?$/) == 0) {
            var pad = function (num) {
                norm = Math.abs(Math.floor(num));
                return (norm < 10 ? '0' : '') + norm;
            },
            tzo = -new Date(d).getTimezoneOffset(),
            sign = tzo >= 0 ? '+' : '-';
    
            var adjusted = d + sign + pad(tzo / 60) + ':' + pad(tzo % 60);
    
            // check whether timezone offsets are equal;
            // if not then the specified date is just within the hour when the clock
            // has been turned forward or back
            if (-new Date(adjusted).getTimezoneOffset() != tzo) {
                // re-adjust
                tzo -= 60;
                adjusted = d + sign + pad(tzo / 60) + ':' + pad(tzo % 60);
            }
    
            return adjusted;
        } else {
            return d;
        }
    }
    
    parseDate = function (/*String*/ d) {
        return new Date(appendTimezone(d));
    }
    
    0 讨论(0)
  • 2020-12-11 03:11

    In addition to @tig's answer (which was exactly what I was looking for):

    Here's the solution for .NetCore 1

    services.AddMvc();
    services.Configure<MvcJsonOptions>(o =>
    {
        o.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
    });
    

    or

    services.AddMvc().AddJsonOptions(o => o.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc);
    

    For .NetCore 1.0.1

    services
        .AddMvcCore()
        .AddJsonFormatters(o => o...);
    
    0 讨论(0)
  • 2020-12-11 03:14

    I ran into this problem, and interpreting the date with the local timezone made a lot more sense than changing to "Z", at least for my application. I created this function to append the local timezone info when it is missing in the ISO date. This can be used in place of new Date(). Partially derived from this answer: How to ISO 8601 format a Date with Timezone Offset in JavaScript?

    parseDate = function (/*String*/ d) {
        if (d.search(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/) == 0) {
            var pad = function (num) {
                norm = Math.abs(Math.floor(num));
                return (norm < 10 ? '0' : '') + norm;
            },
            tzo = -(new Date(d)).getTimezoneOffset(),
            sign = tzo >= 0 ? '+' : '-';
            return new Date(d + sign + pad(tzo / 60) + ':' + pad(tzo % 60));
        } else {
            return new Date(d);
        }
    }
    
    0 讨论(0)
提交回复
热议问题