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