待优化
getDay(type, date){
if (!date || !type) return;
let list = [];
const presentDate = new Date(date),
presentYear = presentDate.getFullYear(),
presentMonth = presentDate.getMonth() + 1;
//获取月日期
if (type === "month") {
list = getMonthDate(presentYear, presentMonth);
}
//获取季度日期
if (type === "quarter") {
// 当前季度
const currQuarter = Math.floor(
presentMonth % 3 == 0 ? presentMonth / 3 : presentMonth / 3 + 1
);
const startMon = (currQuarter - 1) * 3 + 1; //季度月份
for (let mon = startMon; mon <= startMon + 2; mon++) {
list = [...list, ...getMonthDate(presentYear, mon)];
}
}
//获取周日期
if (type === "week") {
let today = presentDate.getDay() !== 0 ? presentDate.getDay() : 7;
list = Array.from(new Array(7), function(val, index) {
return formatDate(
new Date(
presentDate.getTime() - (today - index - 1) * 24 * 60 * 60 * 1000
)
);
});
}
//获取当月的日期集合
function getMonthDate(year, month) {
const totalDay = getTotal(year, month);
//方法一:循环直接拼接输出
//const list = []
//for(let i = 1; i<= totalDay; i++){
// list.push(`${year}-${month}-${i}`)
//}
//return list
//方式二:日期计算 再格式化输出
return Array.from(new Array(totalDay), function(val, index) {
return formatDate(
new Date(
new Date(year, month - 1, 1).getTime() + index * 24 * 60 * 60 * 1000
)
);
});
}
return list;
function getTotal(year, month) {
return new Date(year, month, 0).getDate();
}
function formatDate(date) {
return (
date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate()
);
}
};
getDay("month", "2019.3.5")
image.png
type: month(月)/quarter(季)/week(周)
date:当前日期(日期格式)