Posted By

davidwaterston on 01/14/13


Tagged

javascript date shim ISO-8601


Versions (?)

Convert a Date object to an ISO 8601 formatted string


 / Published in: JavaScript
 

URL: http://jsfiddle.net/davidwaterston/LMxwz/

Javascript which converts a Date object into an ISO 8601 formatted string - 'YYYY-MM-DDTHH:mm:ss.sssZ' - with a fallback for when the function 'toISOString' doesn't exist (e.g. IE 8 or less).

Usage: var now = new Date; console.log(now.toISOString());

Validates clean in JSLint (Edition 2012-12-31).

  1. if (typeof Date.prototype.toISOString !== 'function') {
  2.  
  3. (function () {
  4.  
  5. 'use strict';
  6.  
  7. // Function which takes a 1 or 2-digit number and returns it as a two-character string,
  8. // padded with an extra leading zero, if necessary.
  9. function pad(number) {
  10. var r = String(number);
  11. if (r.length === 1) {
  12. r = '0' + r;
  13. }
  14. return r;
  15. }
  16.  
  17. Date.prototype.toISOString = function () {
  18.  
  19. return this.getUTCFullYear()
  20. + '-' + pad(this.getUTCMonth() + 1)
  21. + '-' + pad(this.getUTCDate())
  22. + 'T' + pad(this.getUTCHours())
  23. + ':' + pad(this.getUTCMinutes())
  24. + ':' + pad(this.getUTCSeconds())
  25. + '.' + String((this.getUTCMilliseconds() / 1000).toFixed(3)).slice(2, 5)
  26. + 'Z';
  27. };
  28.  
  29. }());
  30. }

Report this snippet  

You need to login to post a comment.