getWhatYear.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. var staticStrFirst = require('./staticStrFirst')
  2. var staticStrLast = require('./staticStrLast')
  3. var helperGetDateFullYear = require('./helperGetDateFullYear')
  4. var getWhatMonth = require('./getWhatMonth')
  5. var toStringDate = require('./toStringDate')
  6. var isValidDate = require('./isValidDate')
  7. /**
  8. * 返回前几年或后几年的日期
  9. *
  10. * @param {Date} date 日期或数字
  11. * @param {Number} year 年(默认当前年)、前几个年(数值)、后几个年(数值)
  12. * @param {Number/String} month 获取哪月(null默认当前年)、年初(first)、年末(last)、指定月份(0-11)
  13. * @return {Date}
  14. */
  15. function getWhatYear (date, year, month) {
  16. var number
  17. date = toStringDate(date)
  18. if (isValidDate(date)) {
  19. if (year) {
  20. number = year && !isNaN(year) ? year : 0
  21. date.setFullYear(helperGetDateFullYear(date) + number)
  22. }
  23. if (month || !isNaN(month)) {
  24. if (month === staticStrFirst) {
  25. return new Date(helperGetDateFullYear(date), 0, 1)
  26. } else if (month === staticStrLast) {
  27. date.setMonth(11)
  28. return getWhatMonth(date, 0, staticStrLast)
  29. } else {
  30. date.setMonth(month)
  31. }
  32. }
  33. }
  34. return date
  35. }
  36. module.exports = getWhatYear