Skip to content

Instantly share code, notes, and snippets.

@peterbraden
Created December 23, 2010 00:40
Show Gist options
  • Save peterbraden/752376 to your computer and use it in GitHub Desktop.
Save peterbraden/752376 to your computer and use it in GitHub Desktop.
toISOString with timezone support
Date.prototype.toLocalISOString = function(){
// ISO 8601
var d = this
, pad = function (n){return n<10 ? '0'+n : n}
, tz = d.getTimezoneOffset() //mins
, tzs = (tz>0?"-":"+") + pad(parseInt(tz/60))
if (tz%60 != 0)
tzs += pad(tz%60)
if (tz === 0) // Zulu time == UTC
tzs = 'Z'
return d.getFullYear()+'-'
+ pad(d.getMonth()+1)+'-'
+ pad(d.getDate())+'T'
+ pad(d.getHours())+':'
+ pad(d.getMinutes())+':'
+ pad(d.getSeconds()) + tzs
}
@algesten
Copy link

algesten commented Dec 3, 2013

Doesn't work well for timezones ahead of zulu. I.e. tz < 0. Here's a fix

// ISO8601 in local time zone
var localISOString = function() {

    var d = new Date()
        , pad = function (n){return n<10 ? '0'+n : n;}
        , tz = d.getTimezoneOffset() // mins
        , tzs = (tz>0?"-":"+") + pad(parseInt(Math.abs(tz/60)));

    if (tz%60 != 0)
        tzs += pad(Math.abs(tz%60));

    if (tz === 0) // Zulu time == UTC
        tzs = 'Z';

     return d.getFullYear()+'-'
          + pad(d.getMonth()+1)+'-'
          + pad(d.getDate())+'T'
          + pad(d.getHours())+':'
          + pad(d.getMinutes())+':'
          + pad(d.getSeconds()) + tzs;
};

@bruceblore
Copy link

bruceblore commented Apr 14, 2020

I stumbled across this while needing something like it for my personal project. Here's a much simpler one using ES6.

Date.prototype.toLocalISOString = function () {
    function pad(number) { return ('' + number).padStart(2, '0') }
    return `${this.getFullYear()}-${pad(this.getMonth() + 1)}-${pad(this.getDate())}T${pad(this.getHours())}:${pad(this.getMinutes())}:${pad(this.getSeconds())}`
}

This version does not append the time zone, as I don't need that for my project, but it should be quite easy to add support to it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment