title: Subtracting days/months/years from a Date object
body: <pre><code>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);
  </code></pre>
  
  <p>This is the Javascript code I'm using to work out an expiry date given a user inputted date. Currently, the expiry date is <code>original date minus one day and original year minus X</code>.</p>
  
  <p>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).</p>
  
  <p>I could do something like:</p>
  
  <pre><code>var inputDate = '20/4/2010'.split('/');
  var day       = parseInt(inputDate[0]);
  var month     = parseInt(inputDate[1]);
  var year      = parseInt(inputDate[2]);
  
  if (day &lt; 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);
  </code></pre>
  
  <p>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?</p>
  
  <p>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:</p>
  
  <pre><code>Expiry date is: +3 years
  
  User date is: '14/10/2010'
  Expiry date is: '31/10/2013'
  </code></pre>
  
  <p>I was hoping the <code>Date object</code> would support these calculations but according to <a href="https://developer.mozilla.org/en/JavaScript/Reference/global_objects/date" rel="noreferrer">https://developer.mozilla.org/en/JavaScript/Reference/global_objects/date</a>, it seems not...</p>