Search code examples
javascriptdateiso8601

Extract time from JS Date object without offsetting the Time zone


So we have multiple clients, that are in multiple time zones. I'm pulling some dates from an API, and the dates/times that are in this string are exactly what I need to display. I've been researching this, and digging for some time, and still haven't come up with a clear answer. The string coming in is formatted as such:

"2017-12-29T20:00:00"

What I'm wanting is to extract both the date and time as is, into two strings (no timezone offsetting, no matter where the viewer is located) but am having some issues doing so. Also hoping to format it in the correct fashion as well. Example:

"M/d/yyyy"
"hh:mm AM/PM" (12 hour)

I've tried numerous ways to battle this, and don't really want to just grab substrings, but am half tempted to do so. Any help is appreciated.


Solution

  • Consider just reformatting the string, it avoids all issues with the built-in parser and timezones:

    function reformatTimestamp(s) {
      function z(n){return (n<10?'0':'')+ +n}
      var b = s.split(/\D/);
      var h = b[3]%12 || 12;
      var ap = b[3] < 12? 'AM':'PM';
      return b[1] + '/' + b[2] + '/' + b[0] +
             ' ' + z(h) + ':' + z(b[4]) + ' ' + ap;
    }
    
    console.log(reformatTimestamp('2017-12-29T20:00:00')) // 12/29/2017 08:00 PM

    I think it would be better to pad the month and day with a leading zero (but I'd also use an unambiguous date format like DD-MMM-YYYY rather than the peculiar m/d/y).