week.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import dayjs from 'dayjs';
  2. import weekday from 'dayjs/plugin/weekday';
  3. import isSameOrAfter from 'dayjs/plugin/isSameOrAfter'
  4. import isSameOrBefore from 'dayjs/plugin/isSameOrBefore'
  5. dayjs.extend(weekday)
  6. dayjs.extend(isSameOrAfter)
  7. dayjs.extend(isSameOrBefore)
  8. // 解决苹果电脑本地语言配置
  9. require('dayjs/locale/en');
  10. dayjs.locale('en')
  11. /**
  12. * 根据年月份得到周数据
  13. * @param {String} y 年
  14. * @param {String} m 月
  15. * @param {String} v 当前日期
  16. * @param {Number} t 格式化类型
  17. */
  18. function getWeeksByMonth(y, m, v, t) {
  19. // 2021-12-1是11月的第5周(对这种情况进行判断)
  20. if(dayjs(v).date() < dayjs(v).day()){
  21. m = m-1
  22. }
  23. let len = dayjs(`${y}-${m}`).daysInMonth();
  24. let arr = [],
  25. weekIndex, week;
  26. [...Array(len)].forEach((c, i) => {
  27. let date = dayjs(`${y}-${m}-${i+1}`);
  28. if (date.day() == 1) {
  29. let date_start = date.weekday(1);
  30. let date_end = date.weekday(7);
  31. let index = arr.length + 1;
  32. let start = t ? date_start.format('MM月DD日') : date_start.format('MM-DD');
  33. let end = t ? date_end.format('MM月DD日') : date_end.format('MM-DD');
  34. let obj = {
  35. text: `第${index}周(${start}至${end})`,
  36. year: y,
  37. month: m,
  38. val: `${dayjs(date_start).format('YYYY-MM-DD')}`,
  39. start: start + '(周一)',
  40. end: end + '(周日)',
  41. index: index //1:该月第一周 2:该月第二周
  42. }
  43. arr.push(obj)
  44. week = obj
  45. if (dayjs(v).isSameOrAfter(date_start, 'date') && dayjs(v).isSameOrBefore(
  46. date_end, 'date')) {
  47. week = obj
  48. weekIndex = index;
  49. }
  50. }
  51. })
  52. return {
  53. arr,
  54. weekIndex,
  55. week
  56. }
  57. }
  58. module.exports = {
  59. getWeeksByMonth
  60. }