Created
December 23, 2010 00:40
-
-
Save peterbraden/752376 to your computer and use it in GitHub Desktop.
toISOString with timezone support
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
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
Doesn't work well for timezones ahead of zulu. I.e.
tz < 0
. Here's a fix