week.js 2.1 KB

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