Subtracting days/months/years from a Date object

后端 未结 4 1737
我寻月下人不归
我寻月下人不归 2021-01-04 09:06
var inputDate     = \'20/4/2010\'.split(\'/\');
var dateFormatted = new Date(parseInt(inputDate[2]), parseInt(inputDate[1]), parseInt(inputDate[0]));

var expiryDate         


        
4条回答
  •  情话喂你
    2021-01-04 09:39

    Easy way to see if a date inputed is a valid date:

    var d = Date.parse('4/20/2010');
    if (isNaN(d.valueOf())) {
     alert ("bad date value"); 
    }
    

    Then, here is a dateAdd function that I use regularly. Extends the Date object, so it's easy to use:

    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 passed');
                break;
        }
    }
    

    Then just use:

     var d = new Date();
     d.dateAdd('day', -1).dateAdd('year', 3);
    

    T'da

提交回复
热议问题