index.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334
  1. var parse = require('../parse/index.js')
  2. var getDaysInMonth = require('../get_days_in_month/index.js')
  3. /**
  4. * @category Month Helpers
  5. * @summary Add the specified number of months to the given date.
  6. *
  7. * @description
  8. * Add the specified number of months to the given date.
  9. *
  10. * @param {Date|String|Number} date - the date to be changed
  11. * @param {Number} amount - the amount of months to be added
  12. * @returns {Date} the new date with the months added
  13. *
  14. * @example
  15. * // Add 5 months to 1 September 2014:
  16. * var result = addMonths(new Date(2014, 8, 1), 5)
  17. * //=> Sun Feb 01 2015 00:00:00
  18. */
  19. function addMonths (dirtyDate, dirtyAmount) {
  20. var date = parse(dirtyDate)
  21. var amount = Number(dirtyAmount)
  22. var desiredMonth = date.getMonth() + amount
  23. var dateWithDesiredMonth = new Date(0)
  24. dateWithDesiredMonth.setFullYear(date.getFullYear(), desiredMonth, 1)
  25. dateWithDesiredMonth.setHours(0, 0, 0, 0)
  26. var daysInMonth = getDaysInMonth(dateWithDesiredMonth)
  27. // Set the last day of the new month
  28. // if the original date was the last day of the longer month
  29. date.setMonth(desiredMonth, Math.min(daysInMonth, date.getDate()))
  30. return date
  31. }
  32. module.exports = addMonths