index.js 1.1 KB

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