calendar.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. const getCalendar = function (date) {
  2. // 日历布局 ( 0-6,0代表星期天)
  3. let weeks = [1, 2, 3, 4, 5, 6, 0]
  4. // 拆分日期
  5. let year = date.split("-")[0]
  6. let month = date.split("-")[1]
  7. let day = date.split("-")[2]
  8. // 创建置顶日期的日期对象
  9. let myDate = new Date(date)
  10. // 获取当前月总天数
  11. let days = new Date(year, month, 0).getDate()
  12. // 计算日历面板需要展示上月的天数
  13. let showLastNum = weeks.indexOf(myDate.getDay())
  14. // 计算上月的年、月
  15. let lastYear = Number(month) > 1 ? year : year - 1
  16. let lastMonth = Number(month) > 1 ? Number(month) - 1 : 12
  17. lastMonth = lastMonth < 10 ? '0' + lastMonth : lastMonth
  18. // 计算下月的年、月
  19. let nextYear = Number(month) < 12 ? year : year + 1
  20. let nextMonth = Number(month) < 12 ? Number(month) + 1 : '01'
  21. nextMonth = nextMonth < 10 ? '0' + nextMonth : nextMonth
  22. // 计算上月总天数
  23. let lastMonthDays = new Date(lastYear, lastMonth, 0).getDate()
  24. // 生成日历数组 【年、月、日,是分开的,方便自定义样式】
  25. let calendar = []
  26. for (let i = 0; i < 42; i++) {
  27. if (i < showLastNum) {
  28. let info = {
  29. day: String(lastMonthDays - (showLastNum - 1 - i)),
  30. month: String(lastMonth),
  31. year: String(lastYear)
  32. }
  33. calendar.push(info)
  34. } else if (i < (showLastNum + days)) {
  35. let info = {
  36. day: String(i - showLastNum + 1),
  37. month: String(month),
  38. year: String(year)
  39. }
  40. calendar.push(info)
  41. } else {
  42. let info = {
  43. day: String(i - (showLastNum + days) + 1),
  44. month: String(nextMonth),
  45. year: String(nextYear)
  46. }
  47. calendar.push(info)
  48. }
  49. }
  50. return calendar
  51. }
  52. export default getCalendar