Wrong Date in Javascript

后端 未结 3 1764
悲&欢浪女
悲&欢浪女 2021-01-16 03:10

I am trying to use the fullcalendar.io jquery plugin in my web application. For that, I parse a set of event data into fullcallendar\'s format like this:

Dat         


        
3条回答
  •  说谎
    说谎 (楼主)
    2021-01-16 03:31

    Sadly, when ES5 added the date/time format to JavaScript, they made a mistake: They said that strings without a timezone should be treated as though they were GMT, not local time; but in ISO-8601, which is what they based the format on, strings without timezones are local time.

    ES6 changes it to match ISO-8601, so now we have a problem: Some engines use the ES5 rule (current Firefox, for instance), and some engines use the ES6 rule (current Chrome, for instance).

    So you need to specify a timezone on those strings to parse them reliably, cross-browser:

    • If they're meant to be GMT, it's easy: Just add a Z to them:

      var dt = new Date(entry.date + "Z");
      
    • If they're meant to be local time, it's harder, because you have to allow for DST, so the offset to use varies by the date.

      var dt = new Date(entry.date + "Z");
      dt.setMinutes(dt.getMinutes() + dt.getTimezoneOffset());
      

      I think that still works correctly on DST boundaries, but you'll want to test.

    You can handle this yourself, or you can use a library to handle it for you. There are several choices, just search for "JavaScript date library". One quite popular one at the moment (no pun) is http://momentjs.com.

    Example of #1, just adding Z to make those times GMT/UTC reliably:

    Date.prototype.addHours = function(h) {
      this.setHours(this.getHours() + h);
      return this;
    };
    
    Date.prototype.addMins = function(h) {
      this.setMinutes(this.getMinutes() + h);
      return this;
    };
    
    var data = [{
      "date": "2015-05-01T15:00:00.000",
      "hours": 4,
      "mins": 30
    }, {
      "date": "2015-05-04T15:00:00.000",
      "hours": 4,
      "mins": 30
    }];
    
    data.forEach(function(entry) {
      snippet.log(entry.date + " => " + new Date(entry.date + "Z"));
    });
    
    

    Example of #2, assuming the strings are local time:

    Date.prototype.addHours = function(h) {
      this.setHours(this.getHours() + h);
      return this;
    };
    
    Date.prototype.addMins = function(h) {
      this.setMinutes(this.getMinutes() + h);
      return this;
    };
    
    var data = [{
      "date": "2015-05-01T15:00:00.000",
      "hours": 4,
      "mins": 30
    }, {
      "date": "2015-05-04T15:00:00.000",
      "hours": 4,
      "mins": 30
    }];
    
    data.forEach(function(entry) {
      var dt = new Date(entry.date + "Z");
      dt.setMinutes(dt.getMinutes() + dt.getTimezoneOffset());
      snippet.log(entry.date + " => " + dt);
    });
    
    

提交回复
热议问题