Monday, January 9, 2012

Date Manipulation in JavaScript


There are some methods in JavaScript that will be very useful to do the date manipulation. But we can also have our own prototype for Date object and we can manipulate the date using these functions.

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;
}

How to find Last 10 Days
var today = new Date();
var todate = today;
var fromdate = today.Add("D", -10);

How to find Last month start date and end date
var today = new Date();
today.setDate(1);
var todate = formatDate(today.Add("D", -1));
today.setDate(1);
var fromdate = formatDate(today);
           
How to find last year Start Date and end date
var today = new Date();
today.setDate(1);
today.setMonth(0);
var todate = today.Add("D", -1);
today.setDate(1);
today.setMonth(0);
var fromdate=today;
How to find current quarter of the year
var today = new Date();
var quater = 3 * (Math.floor(today.getMonth() / 3))

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

No comments:

Post a Comment