Convert Date to ISO 8601 String - Node.js Date

Node.js examples for Date:Date Format

Description

Convert Date to ISO 8601 String

Demo Code

Date.prototype.toISO8601String = function (offset) {
    if (!offset) {
        var offset = 'Z';
        var date = this;
    } else {//from w  w w. j a v  a 2  s  .  c  o  m
        var d = offset.match(/([-+])([0-9]{2}):([0-9]{2})/);
        var offsetnum = (Number(d[2]) * 60) + Number(d[3]);
        offsetnum *= ((d[1] == '-') ? -1 : 1);
        var date = new Date(Number(Number(this) + (offsetnum * 60000)));
    }

    var zeropad = function (num) { return ((num < 10) ? '0' : '') + num; }

    var str = "";
    str += date.getUTCFullYear();
    str += "-" + zeropad(date.getUTCMonth() + 1);
    str += "-" + zeropad(date.getUTCDate());
    str += "T" + zeropad(date.getUTCHours()) +
           ":" + zeropad(date.getUTCMinutes());
    str += ":" + zeropad(date.getUTCSeconds());
    str += offset;
    
    return str;
}

Related Tutorials