Skip to content

Instantly share code, notes, and snippets.

@letswritetw
Last active March 15, 2021 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save letswritetw/3ce685ac01b934c398e41ce08fafb8ef to your computer and use it in GitHub Desktop.
Save letswritetw/3ce685ac01b934c398e41ce08fafb8ef to your computer and use it in GitHub Desktop.
dayjs-last-week-month
let currentYear = dayjs().year(); // 本年
let currentMonth = dayjs().month() + 1; // 本月,dayjs 的月份值是「該月 - 1」,因此要 +1 回來
// 本月如果是 1 月,上個月就要是 12 月,並且年份減 1
let lastMonth;
if(currentMonth === 1) {
lastMonth = 12;
currentYear -= 1;
} else {
lastMonth = currentMonth - 1;
}
// 計算每個月的最大天數
// 如果「年」能被 4整除且不被 100整除,或能被 400整除,2月就是 29天,否則為 28天
// 1, 3, 5, 7, 8, 10, 12 為大月,其它為小月
let monthMaxDay;
let bigMonth = [1, 3, 5, 7, 8, 10, 12];
// 2月
if(lastMonth === 2) {
// 潤月 || 非潤月
currentYear % 4 === 0 && currentYear % 100 !== 0 || currentYear % 400 === 0 ? monthMaxDay = 29 : monthMaxDay = 28;
}
else {
// 不是大月就是小月
bigMonth.includes(lastMonth) ? monthMaxDay = 31 : monthMaxDay = 30;
}
// 用 dayjs 進行補 0
let startDate = dayjs(`${currentYear}-${lastMonth}-1`).format('YYYY-MM-DD') + 'T00:00:00';
let endDate = dayjs(`${currentYear}-${lastMonth}-${monthMaxDay}`).format('YYYY-MM-DD') + 'T00:00:00';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment