iOS safari getTime() DST behaviour

落爺英雄遲暮 提交于 2019-12-25 03:19:11

问题


i came across a strange behaviour of iOS 8.2 safari while converting datetime strings to unix ms timestamps during DST transition. Let's say we have js code

function date2unix(dates){
  var len = dates.length;
  var result = [], arr;
  while(len--) {
    arr = dates[len].split(/[- :]/);
    result[len]= (new Date(arr[0], arr[1]-1, arr[2], arr[3],arr[4],arr[5]).getTime());
  }
  return result;
}

var dates =
["2015-03-29 00:00:00","2015-03-29 00:15:00","2015-03-29 00:30:00","2015-03-29 00:45:00","2015-03-29 01:00:00","2015-03-29 01:15:00","2015-03-29 01:30:00","2015-03-29 01:45:00","2015-03-29 03:00:00","2015-03-29 03:15:00","2015-03-29 03:30:00","2015-03-29 03:45:00"];

alert(date2unix(dates))

iOS 8.2 Safari gives ambiguous values (1st == 5th, 2nd == 6th, ...) while chrome 41.0.2272.101 behaves correctly. Note that disputed 2nd hour was omitted in array dates. Could anyone help me with finding workaround, please?

Try: http://jsfiddle.net/q6vd0fos/

Regards


回答1:


The times in question are invalid in your time zone, because they fall into the gap created by the spring-forward daylight saving time transition.

When you do that in JavaScript, the implementation is undefined. Each browser will do something different. Some browsers will skip ahead, some will skip backwards. There's not really much you can do about it, because it's indeterminate behavior.

Another way to think about it is that JavaScript probably should have returned undefined for these values. The only reason it can't do that is because you can't get an undefined as a result of invoking the constructor of a valid object. But logically, the value is undefined.

The below graph, from the DST tag wiki illustrates the gap. This particular chart is of the US Pacific time zone, but the same idea applies to all zones that use DST (but the dates and times will vary). Local time values in this graph starting at 2:00, up until 3:00, are undefined. For example, if you specified 2:30 on this day, some implementations would give you 1:30, and some would give you 3:30.

The right thing to do is to not try to convert times that are invalid.

See also: Garbage in, garbage out.



来源:https://stackoverflow.com/questions/29413022/ios-safari-gettime-dst-behaviour

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!