ISO 8601 javascript Time String Conversion


/ Published in: JavaScript
Save to your folder(s)



Copy this code and paste it in your HTML
  1. /* formatted ISO 8601 timestrings-
  2.  
  3. 2010-06-21T10:41:37.132-04:00
  4. 2010-06-21T14:41:37Z
  5. 2010-06-21
  6. */
  7. Date.fromISO= function(s){
  8. var day, tz, rx= /^(\d{4}\-\d\d\-\d\d([tT][\d:\.]*)?)([zZ]|([+\-])(\d\d):(\d\d))?$/, p= rx.exec(s) || [];
  9. if(p[1]){
  10. day= p[1].split(/\D/).map(function(itm){
  11. return parseInt(itm, 10) || 0;
  12. });
  13. day[1]-= 1;
  14. day= new Date(Date.UTC.apply(Date, day));
  15. if(!day.getDate()) return NaN;
  16. if(p[5]){
  17. tz= parseInt(p[5], 10)*60;
  18. if(p[6]) tz += parseInt(p[6], 10);
  19. if(p[4]== "+") tz*= -1;
  20. if(tz) day.setUTCMinutes(day.getUTCMinutes()+ tz);
  21. }
  22. return day;
  23. }
  24. return NaN;
  25. }
  26. if(![].map){
  27. Array.prototype.map= function(fun, scope){
  28. var L= this.length, A= Array(this.length), i= 0, val;
  29. if(typeof fun== 'function'){
  30. while(i< L){
  31. if(i in this){
  32. A[i]= fun.call(scope, this[i], i, this);
  33. }
  34. ++i;
  35. }
  36. return A;
  37. }
  38. }
  39. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.