1

Starting with a new Date object, is there any way to produce the following string representation using only the Date object's built-in methods -- that is, regular expressions and or substring manipulation not permitted? "2013-02-01T00:00:00-05:00"

Tim
  • 8,669
  • 31
  • 105
  • 183
  • If string concatenation is OK (and there's no good reason for it not to be) then "yes", though time zone deduction can be tricky. – Pointy Feb 20 '13 at 23:43
  • There is no "substring manipulation" in JS, all string values are immutable. – Bergi Feb 20 '13 at 23:52

2 Answers2

4

using only the Date object's built-in methods

No. JavaScript will not let you output ISO 8601 strings with a custom timezone value, .toISOSTring always uses Z (UTC).

You will need to use the various getter methods and construct the string yourself. Building on How do I output an ISO 8601 formatted string in JavaScript? and How to convert ISOString to local ISOString in javascript?:

function customISOstring(date, offset) {
    var date = new Date(date), // copy instance
        h = Math.floor(Math.abs(offset)/60),
        m = Math.abs(offset) % 60;
    date.setMinutes(date.getMinutes() - offset); // apply custom timezone
    function pad(n) { return n < 10 ? '0' + n : n }
    return    date.getUTCFullYear() + '-' // return custom format
        + pad(date.getUTCMonth() + 1) + '-'
        + pad(date.getUTCDate()) + 'T'
        + pad(date.getUTCHours()) + ':'
        + pad(date.getUTCMinutes()) + ':'
        + pad(date.getUTCSeconds())
        + (offset==0 ? "Z" : (offset<0 ? "+" : "-") + pad(h) + ":" + pad(m));
}
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Accepted as the most thorough answer. My thanks to you and to all who responded. – Tim Feb 21 '13 at 01:57
2

It's surprisingly simple, although you will need a helper function to avoid repetition:

var pad = function(n) {return n < 10 ? "0"+n : n;};
var output = date.getFullYear()+"-"+pad(date.getMonth()+1)+"-"+pad(date.getDate())
      +"T"+pad(date.getHours())+":"+pad(date.getMinutes())+":"+pad(date.getSeconds())
      +(date.getTimezoneOffset() > 0 ? "-" : "+")
          +pad(Math.floor(date.getTimezoneOffset()/60))
          +":"+pad(date.getTimezoneOffset()%60);
Jeff B
  • 29,943
  • 7
  • 61
  • 90
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592