getWhatMonth.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. var staticStrFirst = require('./staticStrFirst')
  2. var staticStrLast = require('./staticStrLast')
  3. var staticDayTime = require('./staticDayTime')
  4. var helperGetDateFullYear = require('./helperGetDateFullYear')
  5. var helperGetDateTime = require('./helperGetDateTime')
  6. var helperGetDateMonth = require('./helperGetDateMonth')
  7. var toStringDate = require('./toStringDate')
  8. var isValidDate = require('./isValidDate')
  9. var isNumber = require('./isNumber')
  10. /**
  11. * 返回前几月或后几月的日期
  12. *
  13. * @param {Date} date 日期或数字
  14. * @param {Number} month 月(默认当前月)、前几个月、后几个月
  15. * @param {Number/String} day 获取哪天:月初(first)、月末(last)、指定天数(数值),如果为空,但超过指定月份的天数时,则默认单月最后一天
  16. * @return {Date}
  17. */
  18. function getWhatMonth (date, month, day) {
  19. var monthOffset = month && !isNaN(month) ? month : 0
  20. date = toStringDate(date)
  21. if (isValidDate(date)) {
  22. if (day === staticStrFirst) {
  23. return new Date(helperGetDateFullYear(date), helperGetDateMonth(date) + monthOffset, 1)
  24. } else if (day === staticStrLast) {
  25. return new Date(helperGetDateTime(getWhatMonth(date, monthOffset + 1, staticStrFirst)) - 1)
  26. } else if (isNumber(day)) {
  27. date.setDate(day)
  28. }
  29. if (monthOffset) {
  30. var currDate = date.getDate()
  31. date.setMonth(helperGetDateMonth(date) + monthOffset)
  32. if (currDate !== date.getDate()) {
  33. // 当为指定天数,且被跨月了,则默认单月最后一天
  34. date.setDate(1)
  35. return new Date(helperGetDateTime(date) - staticDayTime)
  36. }
  37. }
  38. }
  39. return date
  40. }
  41. module.exports = getWhatMonth