code_junkie

How can I convert a date value in UTC format to a date object in Javascript

Nov 14th, 2011
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.76 KB | None | 0 0
  1. var ISODate = {
  2. convert : function (input){
  3. if (!(typeof input === "string")) throw "ISODate, convert: input must be a string";
  4. var d = input.match(/^(d{4})-(d{2})-(d{2})[T ](d{2}):(d{2}):(d{2}(?:.d+)?)(Z|(([+-])(d{2}):(d{2})))$/i);
  5. if (!d) throw "ISODate, convert: Illegal format";
  6. return new Date(
  7. Date.UTC(d[1],d[2]-1,d[3],d[4],d[5],d[6]|0,(d[6]*1000-((d[6]|0)*1000))|0,d[7]) +
  8. (d[7].toUpperCase() ==="Z" ? 0 : (d[10]*3600 + d[11]*60) * (d[9]==="-" ? 1000 : -1000))
  9. );
  10. },
  11. format : function(t,utc){
  12. if (typeof t === "string") t = this.convert(t);
  13. if (!(t instanceof Date)) throw "ISODate, format: t is not a date object";
  14. t = utc ?
  15. [t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate(),t.getUTCHours(),t.getUTCMinutes(),t.getUTCSeconds()] :
  16. [t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds()];
  17.  
  18. return this.month[t[1]] + " " +this.ordinal(t[2]) + ", " +t[0] +
  19. " @ " + this.clock12(t[3],t[4]);
  20. },
  21. month:["January","February","March","April","May","June","July","September","October","November","December"],
  22. ordinal:function(n) {
  23. return n+(["th","st","nd","rd"][(( n % 100 / 10) | 0) ===1 ? 0 : n % 10 < 4 ? n % 10 : 0 ]);
  24. },
  25. clock12:function(h24,m,s){
  26. h24%=24;
  27. var h12 = h24 % 12;
  28. if (h12===0) h12=12;
  29. return h12 + ":" +
  30. (m<10 ? "0" + m : m) +
  31. (isFinite(s) ? ":" + (s<10?"0"+s:s): "") +
  32. (h24<12 ? "AM":"PM");
  33. }
  34. };
  35.  
  36. //Shows the date in the users timezone:
  37. alert(ISODate.format("2007-09-21T14:15:34.058-07:00"));
  38.  
  39. //Show the date in UTC (Timezone Z, 00:00)
  40. alert(ISODate.format("2007-09-21T14:15:34.058-07:00",true));
Add Comment
Please, Sign In to add comment