Why do I get wrong result from function?

2020-05-03 11:08发布

I has this objects array:

var data=[{Id:540, MeasureDate:"2016-06-27T15:06:47"},
          {Id:541, MeasureDate:"2016-06-27T12:24:39"}];

I call this function:

var latestdate = updateLatestDate(data);

function updateLatestDate(sensorsData) {
    return new Date(Math.max.apply(null, sensorsData.map(function (e) {
        return new Date(e.MeasureDate);
    }))).toISOString();
}

the function updateLatestDate returns latest date and convert it to ISOString().

But the problem is that I get diffrent results if I use it in chrome and in IE11.

In chrome the latestdate variable is "2016-06-27T15:06:47.000Z"

In IE the latestdate variable is "2016-06-27T12:06:47.000Z"

The function updateLatestDate works perfect in chrome but it returns wrong result in IE, it seems to me that the problem might be with Math.max.apply function.

Any idea why I get wrong result in IE and how can I fix it?

2条回答
你好瞎i
2楼-- · 2020-05-03 11:10

The reason is you don't have a timezone specified in your ISO8601 timestamp. Chrome defaults to UTC and and IE to local when it is not specified (or the other way around, I forget).

You can either:

a) add 'Z' to the end of your timestamp to specify UTC or add another timezone ( see wikipedia for valid formats https://en.m.wikipedia.org/wiki/ISO_8601)

b) use momentjs which I believe will standardize the behavior across the browsers.

查看更多
可以哭但决不认输i
3楼-- · 2020-05-03 11:26

As mentioned by @elliot moment can help you. Check this solution:

(function() {

  var data = [{
    Id: 540,
    MeasureDate: "2016-06-27T13:06:47"
  }, {
    Id: 541,
    MeasureDate: "2016-06-27T12:24:39"
  }, {
    Id: 540,
    MeasureDate: "2016-06-27T13:16:47"
  }];

  function getMaxInArray(items, max) {
    if (items.length) {
      var item = items.splice(0, 1)[0];
      return getMaxInArray(items, Math.max(item, !!max ? max : item));
    }
    return max;
  }

  var dates = data.map(function(x) { return moment(x.MeasureDate); });
  var latest = moment(getMaxInArray(dates));

  console.log(latest.format());

}());

http://plnkr.co:80/oeMDJYzDGkgm4cX4NIpo

查看更多
登录 后发表回答