Keep the time in the specified local time zone and store its UTC offset - Node.js Date

Node.js examples for Date:Time

Description

Keep the time in the specified local time zone and store its UTC offset

Demo Code


// __BEGIN_LICENSE__
// Copyright (C) 2008-2010 United States Government as represented by
// the Administrator of the National Aeronautics and Space Administration.
// All Rights Reserved.
// __END_LICENSE__

/**********************************************************************
 * From "Dan's Network"/*from  w w w  . j  av  a  2s .c o  m*/
 **********************************************************************/

/* Blog post contents: In need of a JavaScript function that would parse
 * an ISO8601 compliant date, I came across an attempt
 * (http://delete.me.uk/2005/03/iso8601.html) and rewrote it (because
 * I'm all about reinventing the wheel). My function extends the Date
 * object and allows you to pass in an ISO8601 date
 * (2008-11-01T20:39:57.78-06:00). The function will then return the
 * Date. In the date string argument the dashes and colons are
 * optional. The decimal point for milliseconds is mandatory (although
 * specifying milliseconds t). If a timezone offset sign must be
 * included. This function should also work with iCalendar(RFC2445)
 * formatted dates. If a the date string t match the format, there will
 * be a final attempt to parse it with the built in Date.parse()
 * method.
 *
 * http://dansnetwork.com/2008/11/01/javascript-iso8601rfc3339-date-parser/
 */

// Lightly modified to keep the time in the specified local time zone
// and store its UTC offset explicitly in the tzinfo and utcoffset
// fields, sort of like Python datetime. -Trey

Date.prototype.setIso8601 = function (dString) {
    var regexp = /(\d\d\d\d)(-)?(\d\d)(-)?(\d\d)(T)?(\d\d)(:)?(\d\d)(:)?(\d\d)(\.\d+)?(Z|([+-])(\d\d)(:)?(\d\d))/;
    if (dString.toString().match(new RegExp(regexp))) {
        var d = dString.match(new RegExp(regexp));
        this.setDate(1);
        this.setFullYear(parseInt(d[1],10));
        this.setMonth(parseInt(d[3],10) - 1);
        this.setDate(parseInt(d[5],10));
        this.setHours(parseInt(d[7],10));
        this.setMinutes(parseInt(d[9],10));
        this.setSeconds(parseInt(d[11],10));
        if (d[12]) {
            this.setMilliseconds(parseFloat(d[12]) * 1000);
        } else {
            this.setMilliseconds(0);
        }
        if (d[13] == 'Z') {
            this.tzinfo = 'UTC';
            this.utcoffset = 0;
        } else {
            this.tzinfo = d[14] + d[15] + d[17];
            this.utcoffset = (d[15] * 60) + parseInt(d[17],10);
            this.utcoffset *= ((d[14] == '-') ? -1 : 1);
        }
    } else {
        this.setTime(Date.parse(dString));
    }
    return this;
};

Related Tutorials