Monday, January 9, 2012

DateAdd, DateSub functions in JavaScript


There is no direct dateadd(), datediff() methods in JavaScript. But we can create our own prototype for Date functions, then we can use it as like as normal method like in C#, VB.Net , etc…

Date.prototype.Add = function (strInterval, intIncrement) {
    switch (strInterval) {
        case "M":
            this.setMonth(parseInt(this.getMonth()) + parseInt(intIncrement));
            break;
        case "D":
            this.setDate(parseInt(this.getDate()) + parseInt(intIncrement));
            break;
        case "Y":
            this.setYear(parseInt(this.getYear()) + parseInt(intIncrement));
            break;
        case "h":
            this.setHours(parseInt(this.getHours()) + parseInt(intIncrement));
            break;
        case "m":
            this.setMinutes(parseInt(this.getMinutes()) + parseInt(intIncrement));
            break;
        case "s":
            this.setSeconds(parseInt(this.getSeconds()) + parseInt(intIncrement));
            break;
        case "uM":
            this.setUTCMonth(parseInt(this.getUTCMonth()) + parseInt(intIncrement));
            break;
        case "uD":
            this.setUTCDate(parseInt(this.getUTCDate()) + parseInt(intIncrement));
            break;
        case "uY":
            this.setUTCFullYear(parseInt(this.getUTCFullYear()) + parseInt(intIncrement));
            break;
        case "uh":
            this.setUTCHours(parseInt(this.getUTCHours()) + parseInt(intIncrement));
            break;
        case "um":
            this.setUTCMinutes(parseInt(this.getUTCMinutes()) + parseInt(intIncrement));
            break;
        case "us":
            this.setUTCSeconds(parseInt(this.getUTCSeconds()) + parseInt(intIncrement));
            break;
    }
    return this;
}


To add 3 days
var today = new Date();
today.Add("D", 3);

To sub 3 days
var today = new Date();
today.Add("D", -3);

Like this we can add Days, Months, Years, Hours, Minutes, and Seconds.

I hope this article will be very helpful to all. Thanks for reading this article.

“Keep reading and share the knowledge”  
“Grow more trees to save the Earth”

No comments:

Post a Comment