To return a new Date object from a string of any ISO 8601, which can range from "2010-01-10" to "2010-01-10T19: 42: 45.5-05-05: 00, several templates need to be considered.
The division of seconds (preceded by a decimal point) and the local offset TimeZone (preceded by "+" or "-") are three quarters of the code:
Date.parseISO= function(iso){ var z, tem, TZ, ms= 0; z= /:/.test(iso)? ' GMT': ''; ms=/(\.\d+)/.exec(iso); if(ms){ ms= ms[1]; iso= iso.replace(ms,''); ms= Math.round(1000*ms); } if(z && !/Z$/.test(iso)){ TZ=/:\d\d((\-|\+)(\d\d):(\d\d))$/.exec(iso); if(TZ){ tem= TZ[3]*60+(+TZ[4]); z+= TZ[2]+tem; iso= iso.replace(TZ[1],''); } } iso= iso.replace(/[^\d:]/g,' ')+z; var stamp= Date.parse(iso); if(!stamp) throw iso +' Unknown date format'; return new Date(stamp+ms); }
// Getting the ISO string from javascript Date is the easiest if you use UTC (GMT)
Date.prototype.toISO= function(time){ var i=0, D= this, A= [D.getUTCFullYear(), D.getUTCMonth(), D.getUTCDate(), D.getUTCHours(), D.getUTCMinutes(), D.getUTCSeconds()]; ++A[1]; var T= A.splice(3); A= A.join('-'); if(time){ if(time==2) T.pop(); while(i< T.length){ if(T[i]<10) T[i]= '0'+T[i]; ++i; } if(time==4)T[2]= T[2]+'.'+ Math.round((this.getMilliseconds()/1000)*1000); return A+'T'+T.join(':')+'Z'; } return A; }
kennebec
source share