Michael LB
Michael LB

Reputation: 2722

Add days, weeks, months to date using jQuery

I have a form which lets the user select an invoice date and payment terms. The payment terms are; 1 week from invoice date, 4 weeks from invoice date, 1 month from invoice date, etc.

When the user has selected an invoice date and the payment terms I then want to generate the invoice due date.

My question is, how do I add to a date in jQuery and how do I do it in a reliable way. For example, taking into account leap years and the varying number of days in each month. For example, adding 1 month to October 31st should be November 30th and not November 31st.

I have found a few solutions by searching Google but they seem to fail on leap years, etc.

Upvotes: 0

Views: 4773

Answers (2)

aahhaa
aahhaa

Reputation: 2275

Javascript have default date obj you can use as such. moment.js is a neat choice too.

    var date = new Date();

    // add a day or anyday you like 
    date.setDate(date.getDate() + 1);

    document.write(date);

Upvotes: 0

Andre Pena
Andre Pena

Reputation: 59416

jQuery is not for DateTime manipulation. It's for querying and manipulating DOM objects. For what you need, you can either implement that yourself, or use a specialized third-party library.

Moment.js is pretty neat.

Examples:

moment().subtract(10, 'days').calendar(); // 06/12/2015
moment().subtract(6, 'days').calendar();  // Last Tuesday at 1:51 PM
moment().subtract(3, 'days').calendar();  // Last Friday at 1:51 PM
moment().subtract(1, 'days').calendar();  // Yesterday at 1:51 PM
moment().calendar();                      // Today at 1:51 PM
moment().add(1, 'days').calendar();       // Tomorrow at 1:51 PM
moment().add(3, 'days').calendar();       // Thursday at 1:51 PM
moment().add(10, 'days'

More examples here: http://momentjs.com/

Upvotes: 3

Related Questions