Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtracting days/months/years from a Date object

var inputDate     = '20/4/2010'.split('/');
var dateFormatted = new Date(parseInt(inputDate[2]), parseInt(inputDate[1]), parseInt(inputDate[0]));

var expiryDate = (dateFormatted.getDate() - 1) + '/' + dateFormatted.getMonth() + '/' + (dateFormatted.getFullYear() + year);

This is the Javascript code I'm using to work out an expiry date given a user inputted date. Currently, the expiry date is original date minus one day and original year minus X.

The problems with this code, firstly, it doesn't take into account invalid dates. For example, if the user supplied date is '1/10/2010', the expiry date will be '0/10/2013' (assuming the expiry date is +3 years).

I could do something like:

var inputDate = '20/4/2010'.split('/');
var day       = parseInt(inputDate[0]);
var month     = parseInt(inputDate[1]);
var year      = parseInt(inputDate[2]);

if (day < 1)
{
    if (month == ...)
    {
        day   = 31
        month = month - 1;
    }
    else
    {
        day   = 30
        month = month - 1;
    }
}

var dateFormatted = new Date(parseInt(inputDate[2]), parseInt(inputDate[1]), parseInt(inputDate[0]));
var expiryDate    = (dateFormatted.getDate() - 1) + '/' + dateFormatted.getMonth() + '/' + (dateFormatted.getFullYear() + year);

But more problems arise... Firstly, the code gets a little convoluted. Secondly, this check would have to be done on the day. and then the month. Is there a cleaner, simpler way?

Also, there's a certain circumstance that would involve me needing to calculate the expiry date to the 'end of the month' for that date. For example:

Expiry date is: +3 years

User date is: '14/10/2010'
Expiry date is: '31/10/2013'

I was hoping the Date object would support these calculations but according to https://developer.mozilla.org/en/JavaScript/Reference/global_objects/date, it seems not...

like image 491
dave Avatar asked Nov 08 '10 06:11

dave


People also ask

How do you subtract days from date objects?

To subtract days to a JavaScript Date object, use the setDate() method. Under that, get the current days and subtract days. JavaScript date setDate() method sets the day of the month for a specified date according to local time.

How do you find the month and year from a date object?

To get the year, month and day from a date object:Call the getFullYear() method to get the year. Call the getMonth() method to get an integer from 0 (January) to 11 (December). Call the getDate() method to get the day of the month.

How do I subtract months and months in Excel?

To subtract months, enter a negative number as the second argument. For example, =EDATE("9/15/19",-5) returns 4/15/19. For this example, you can enter your starting dates in column A. Enter the number of months to add or subtract in column B.


2 Answers

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

like image 181
Noah Avatar answered Nov 15 '22 19:11

Noah


A similar question has been answered here:

How to add/subtract dates with javascript?

Similar thing can be done for months and years.

For e.g.

     var date = new Date('2011','01','02');
     alert('the original date is '+date);
     var newdate = new Date(date);
     newdate.setMonth(newdate.getMonth() - 7);
     var nd = new Date(newdate);
     alert('the new date is '+nd);
like image 36
Gunjit Avatar answered Nov 15 '22 17:11

Gunjit