1.输出今天是今年的第多少天,也可查询到年底还有多少天
function getDays(cur, prv) {
return (Math.abs((new Date(cur)).getTime() - (new Date(prv)).getTime()) / (60*60*24*1000)).toFixed() // 日期时间戳相减获取差值,除于一天的时间戳,获取正整数
}
alert(getDays('2021-05-14', '2021-01-01'))
alert(getDays('2021-01-01', '2021-05-14')) // 因为添加了绝对值的计算,所以不涉及到日期前后顺序的校验
2.输出今天是今年的第多少周
function getDays(cur, prv) {
return (Math.abs((new Date(cur)).getTime() - (new Date(prv)).getTime() + 60*60*24*1000) / (7*60*60*24*1000)).toFixed()
}
alert(getDays('2021-05-17', '2021-01-01'))
3.输出两个时间段中的所有月份
function getYears(startDate, endDate) { // 获取两个年月之间的所有月份
let [startYear, startMonth] = startDate.split('-')
let [endYear, endMonth] = endDate.split('-')
// 同一年的中间月份
if (endYear === startYear) {
return Array.from({length: endMonth - startMonth + 1}, (k, v) => `${endYear}-${(v + +startMonth + '').padStart(2, 0)}`)
}
// 非同年
let allMonths = []
// 开始年的月份
Array.from({length: 13 - startMonth}, (k, v) => allMonths.push(`${startYear}-${(v + +startMonth + '').padStart(2, 0)}`))
// 中间年月
if (endYear - startYear > 1) {
for (let year = +startYear + 1; year < endYear; year++) {
Array.from({length: 12}, (k, v) => allMonths.push(`${year}-${(v + 1 + '').padStart(2, 0)}`))
}
}
// 结束年月
Array.from({length: +endMonth}, (k, v) => allMonths.push(`${endYear}-${(v + 1 + '').padStart(2, 0)}`))
return allMonths;
}
getYears('2020-02', '2021-05')//["2020-02", "2020-03", "2020-04", "2020-05", "2020-06", "2020-07", "2020-08", "2020-09", "2020-10", "2020-11", "2020-12", "2021-01", "2021-02", "2021-03", "2021-04", "2021-05"]