Click here to Skip to main content
15,885,278 members
Articles / Programming Languages / Javascript
Tip/Trick

JavaScript date helper class

Rate me:
Please Sign up or sign in to vote.
1.00/5 (1 vote)
12 Oct 2011CPOL 11.7K   2  
Save the following code to a .js file or add to an existing one you might have ...
Save the following code to a .js file or add to an existing one you might have:

C#
Date.prototype.toNoon = function () {
    this.setHours(12, 0, 0, 0);
    return this;
}
Date.prototype.dateAdd = function (interval, n) {
    if (isNaN(n = parseInt(n, 10))) {
        //Only accpets numbers
        throw "The second parameter must be a number. \n You passed: " + n;
        return null;
    }

    var dt = new Date(this);

    switch (interval.toLowerCase()) {
        case "y":
            {// year
                this.setFullYear(this.getFullYear() + n);
                break;
            }
        case "q":
            { // quarter
                this.setMonth(this.getMonth() + (n * 3));
                break;
            }
        case "m":
            { // month
                this.setMonth(this.getMonth() + n);
                break;
            }
        case "d":   // day / day of year
        case "w":
            { // weekday
                var y = this.getFullYear();
                var m = this.getMonth();
                var d = this.getDate();
                var newDate = new Date(y, m, d, 12, 0, 0);
                newDate.setDate(d + n);
                this.setTime(newDate.getTime());

                //this.setUTCDate(this.getUTCDate() + n);
                //var diff = this.getTime() - (dt.getTime() + (n*84600000));
                //this.setMilliseconds(diff);
                break;
            }
        case "ww":
            { // week of year
                this.setDate(this.getDate() + (n * 7));
                break;
            }
        case "h":
            { // hour
                this.setHours(this.getHours() + n);
                break;
            }
        case "n":
            { // minute
                this.setMinutes(this.getMinutes() + n);
                break;
            }
        case "s":
            { // second
                this.setSeconds(this.getSeconds() + n);
                break;
            }
        case "ms":
            { // milli second
                this.setMilliseconds(this.getMilliseconds() + n);
                break;
            }
        default:
            {
                //list of elegible intervals.
                throw "The first parameter must be a string from this list: \n" +
                    "y, q, m, d, w, ww, h, n, s, or ms. You passed: " + interval;
                return false;
            }
    }
    switch (interval.toLowerCase()) {
        case "d":   // day / day of year
        case "w":
            { // weekday
                break;
            }
        default:
            {
                if (this.getDate() != dt.getDate()) {
                    this.setDate(0);
                }
            }
    }
    return this;
}
Date.prototype.addDays = function (n) {
    return this.dateAdd("d", n);
}
Date.prototype.addMonths = function (n) {
    return this.dateAdd("m", n);
}
Date.prototype.firstDayOfMonth = function () {
    var y = this.getFullYear();
    var m = this.getMonth();
    this.setTime((new Date(y, m, 1, 12, 0, 0)).getTime())
    return this;
}
Date.prototype.lastDayOfMonth = function () {
    return this.firstDayOfMonth().addMonths("m", 1).addDays("d", -1);
}
Date.prototype.isBefore = function (date, orEqual) {
    return this.getTime() < date.getTime() || (orEqual && this.getTime() == date.getTime());
}
Date.prototype.isAfter = function (date, orEqual) {
    return this.getTime() > date.getTime() || (orEqual && this.getTime() == date.getTime());
}
Date.prototype.isBetween = function (a, b, orEqual) {
    return a.isBefore(this, orEqual) && this.isBefore(b, orEqual);
}
Date.prototype.range = function (date) {
    var range = {};
    if (this.isBefore(date)) {
        range["fromDate"] = new Date(this);
        range["toDate"] = new Date(date);
    } else {
        range["fromDate"] = new Date(date);
        range["toDate"] = new Date(this);
    }

    function overlaps(a, b) {
        return contains(a) || contains(b) || (a.isBefore(range["fromDate"], true) && range["toDate"].isBefore(b, true));
    }
    function contains(a) {
        return isBetween(a, range["fromDate"], range["toDate"]) || isBetween(a, range["toDate"], range["fromDate"]);
    }
    function isBetween(c, a, b) {
        return c.isBetween(a, b, true);
    }

    return {
        overlaps: overlaps,
        contains: contains,
        days: function () { return ((range["toDate"] - range["fromDate"]) / (1000 * 60 * 60 * 24)); },
        fromDate: function () { return range["fromDate"]; },
        toDate: function () { return range["toDate"]; }
    }
}
Date.prototype.monthNames = function () {
    return new Array("January", "February", "March",
        "April", "May", "June", "July", "August", "September",
        "October", "November", "December");
}
Date.prototype.monthName = function (shrt) {
    var idx = this.getMonth();
    var name = "";
    if (idx >= this.monthNames.length || idx < 0)
        return "";
    name = this.monthNames[idx];
    if (!shrt)
        return name;
    else
        return name.substr(0, 3);
}


To use, just use a Date class instance, e.g.

C#
var dt = new Date();
dt.addDays(1);


This will add one day to the current date.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer Codely
South Africa South Africa
Me, a disorder of the brain that results in a disruption in a person's thinking, mood, and ability to relate to others.

Comments and Discussions

 
-- There are no messages in this forum --