function range(start, end) {
start = Number(start)
end = Number(end)
if (start > end) return []
return new Array(end - start + 1).fill().map((item, index) => index + start)
}
function dayRange(year, month, startDay = 1, endDay, flag) {
if(flag){
endDay = endDay
}else{
if (month === 2) {
if (year % 4 === 0) {
endDay = endDay || 29
} else {
endDay = endDay || 28
}
} else if ([1, 3, 5, 7, 8, 10, 12].includes(month)) {
endDay = 31
} else {
endDay = 30
}
}
return range(startDay, endDay)
}
//开始or结束日期可自定义
export default function createPickerData(startDate = '2017-01-01', endDate = '2049-12-31', isSetEndDay=false) {
const [startYear, startMonth, startDay] = startDate.split('-').map(Number)
const [endYear, endMonth, endDay] = endDate.split('-').map(Number)
if (startYear === endYear) {
if (startMonth === endMonth) {
return [
{
[startYear]: [
{
[startMonth]: dayRange(startYear, startMonth, startDay, endDay, isSetEndDay)
}
]
}
]
}
return [
{
[startYear]: [
{
[startMonth]: dayRange(startYear, startMonth, startDay)
},
...range(startMonth + 1, endMonth - 1).map(month => ({
[month]: dayRange(startYear, month)
})),
{
[endMonth]: dayRange(startYear, startMonth, 1, endDay, isSetEndDay)
}
]
}
]
}
return [
{
[startYear]: range(startMonth, 12).map(month => ({
[month]: dayRange(startYear, month, month === startMonth ? startDay : 1)
}))
},
...range(startYear + 1, endYear - 1).map(year => ({
[year]: range(1, 12).map(month => ({
[month]: dayRange(year, month)
}))
})),
{
[endYear]: range(1, endMonth).map(month => ({
[month]: dayRange(endYear, month, 1, month === endMonth ? endDay : null, isSetEndDay)
}))
}
]
}
网友评论