Here's the sample code:
var d = new Date("2010-06-09T19:20:30+01:00");
document.write(d);
On FF3.6 this will give you:
Wed Jun 09 2010 14:20:30 GMT-0400 (EST)
Other browers tested; Chrome 5, Safari 4, IE7 give:
Invalid Date
I know there i开发者_如何学Gos limited to no support for ISO8601 dates, but does anyone know what and/or where the difference is in FF3.6 that allows this to work?
My thought is that FF is just stripping out what it doesn't understand while the others are not.
Has anyone else seen this and/or getting different results from the test script?
ECMAScript 5th edition (see §15.9.1.15) adds some support for ISO-8601, and Mozilla has apparently jumped on it (they may even have been the ones pushing it). I didn't think they'd added it to the constructor, and the support is supposed to be a bit simplified, but that doesn't mean Mozilla can't go with the spirit rather than the letter and take anything it can figure out — or thinks it can figure out. The actual format supported in the spec is YYYY-MM-DDTHH:mm:ss.sssZ
. Your sample date is not quite a match.
ISO 8601 is often used to pass time/date info between systems
It allows yyyy-mm-dd alone for midnight GMT of that date,
or the date followed by 'T' and time data,
with optional seconds and milliseconds (after ',').
yyyy-mm-ddThh:mm
yyyy-mm-ddThh:mm:ss.xxx
You finish with either Z for greenwich time, nothing, also for Greenwich time, or a + or - and the hh:mm offset from GMT.
You can make your own method- this passes back the local Date, using the built in method if it is available- only firefox, so far.
Date.ISO= function(s){
var D= new Date(s);
if(D.getDate()) return D;
var M= [], min= 0,
Rx= /([\d:]+)(\.\d+)?(Z|(([+\-])(\d\d):(\d\d))?)?$/;
D= s.substring(0, 10).split("-");
if(s.length> 11){
M= s.substring(11).match(Rx) || [];
if(M[1]) D= D.concat(M[1].split(":"));
if(M[2]) D.push(Math.round(M[2]*1000));
}
D= D.map(function(itm){return parseInt(itm, 10);});
D[1]-= 1;
while(D.length < 7) D.push(0);
if(M[4]){
min= parseInt(M[6])*60 + parseInt(M[7], 10);
if(M[5]== "+") min*= -1;
}
D= new Date(Date.UTC.apply(Date, D));
if(!D.getDate()) throw "Bad Date- " + s;
if(min) D.setMinutes(D.getMinutes()+ min);
return D;
}
//tests
var s= "2010-06-09T19:20:30+01:00";
alert(Date.ISO(s).toUTCString());
/* value: (String) Safari 5.0: Wed, 09 Jun 2010 18:20:30 GMT
MSIE 8.0: Wed, 9 Jun 2010 18:20:30 UTC
Chrome 5.0.375.70: Wed, 09 Jun 2010 18:20:30 GMT
Opera 10.53: Wed, 09 Jun 2010 18:20:30 GMT
Firefox 3.6.3: Wed, 09 Jun 2010 18:20:30 GMT */
Note- To work in IE (and older browsers) you'll need to fake the array map method-
if(![].map){
Array.prototype.map= function(fun, scope){
var L= this.length, A= Array(this.length), i= 0, val;
if(typeof fun== 'function'){
while(i< L){
if(i in this){
A[i]= fun.call(scope, this[i], i, this);
}
++i;
}
return A;
}
}
}
精彩评论