date

by bhupendra negi

HTML

<input type="text" id = "strDate" placeholder="Start Date"/>
<input type="text" id = "endDate" placeholder = "End Date"/>
<input type="button" id ="btnGet" value = "Get Dates"/>

JavaScript

$(document).ready(function () {
    $("#btnGet").click(function() {
       
        var d = new Date();
        d.dateAdd('month', -6);
        console.log(d.yyyymmdd());
        $("#strDate").val(d);
     
        var d1= new Date();
        d1.dateAdd('day',15)
       console.log(d1.yyyymmdd());
        $("#endDate").val(d1);
        
        
      });



});

Date.prototype.yyyymmdd = function() {         
                                
        var yyyy = this.getFullYear().toString();                                    
        var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based         
        var dd  = this.getDate().toString();             
                            
        return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]);
   };  



Date.prototype.dateAdd = function(size,value) {
    value = parseInt(value);
    var incr = 0;
    switch (size) {
        case 'day':
            incr = value * 24;
            this.dateAdd('hour',incr);
            break;
        case 'hour':
            incr = value * 60;
            this.dateAdd('minute',incr);
            break;
        case 'week':
            incr = value * 7;
            this.dateAdd('day',incr);
            break;
        case 'minute':
            incr = value * 60;
            this.dateAdd('second',incr);
            break;
        case 'second':
            incr = value * 1000;
            this.dateAdd('millisecond',incr);
            break;
        case 'month':
            value = value + this.getUTCMonth();
            if (value/12>0) {
                this.dateAdd('year',value/12);
                value = value % 12;
            }
            this.setUTCMonth(value);
            break;
        case 'millisecond':
            this.setTime(this.getTime() + value);
            break;
        case 'year':
            this.setFullYear(this.getUTCFullYear()+value);
            break;
        default:
            throw new Error('Invalid date increment...