dateFormate.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. export function getPrevious8Weeks(currentDate) {
  2. // 确保传入的是Date对象
  3. const date = new Date(currentDate);
  4. // 获取当前日期是星期几(0-6,0代表周日)
  5. const currentDay = date.getDay();
  6. // 计算当前周的周一(将周日作为一周的最后一天)
  7. const mondayOffset = currentDay === 0 ? -6 : 1 - currentDay;
  8. const currentMonday = new Date(date);
  9. currentMonday.setDate(date.getDate() + mondayOffset);
  10. const result = [];
  11. // 生成前8个自然周的日期范围(从上一周开始,不包含当前周)
  12. for (let i = 1; i <= 8; i++) {
  13. const weekStart = new Date(currentMonday);
  14. weekStart.setDate(currentMonday.getDate() - i * 7);
  15. const weekEnd = new Date(weekStart);
  16. weekEnd.setDate(weekStart.getDate() + 6);
  17. // 格式化日期为 YYYY-MM-DD
  18. const startStr = formatDate(weekStart);
  19. const endStr = formatDate(weekEnd);
  20. result.push([startStr, endStr]);
  21. }
  22. return result;
  23. }
  24. // 辅助函数:格式化日期为 YYYY-MM-DD
  25. function formatDate(date) {
  26. const year = date.getFullYear();
  27. const month = String(date.getMonth() + 1).padStart(2, '0');
  28. const day = String(date.getDate()).padStart(2, '0');
  29. return `${year}-${month}-${day}`;
  30. }