0

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.

Michael LB
  • 2,715
  • 4
  • 23
  • 38

2 Answers2

3

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/

Andre Pena
  • 56,650
  • 48
  • 196
  • 243
0

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);
aahhaa
  • 2,240
  • 3
  • 19
  • 30
  • Exact, I need to precise that, in javascript, january is the month "0" and december is counted as "11". – rafatic Jun 22 '15 at 16:56
  • date.getMonth(); will return month as number, jan will be 1, dec will be 12 but you can always `-1`. to get base 0. – aahhaa Jun 22 '15 at 17:00
  • sorry, javascript month is already base 0, so no math needed... disregard comment before. – aahhaa Jun 22 '15 at 17:04