前言
现有一个日期字符串,如:2000-10-24
,求这个日期是当年的第几天
实现
// 参数格式检查
function verifyDate(dateStr) {
// 检查格式
const datePattern = /^\d{4}-\d{2}-\d{2}$/
if (!datePattern.test(dateStr)) {
return "参数格式错误!"
}
// 检查数据
const [year, month, day] = dateStr.split("-").map(Number)
if (month < 1 || month > 12) {
return "月份格式错误!"
}
const maxDay = new Date(year, month, 0).getDate()
if (day < 1 || day > maxDay) {
return "日期格式错误!"
}
}
// 是否闰年
function isRunYear(year) {
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0
}
// 天数枚举
const DayMap = {
31: [1, 3, 5, 7, 8, 10, 12],
30: [4, 6, 9, 11],
29: [2],
28: [2],
}
// const month_31 = [1, 3, 5, 7, 8, 10, 12]
// const month_30 = [4, 6, 9, 11]
function getDayMap(year) {
const obj = {
};
Object.keys(DayMap).forEach(value => {
DayMap[value].forEach(key => {
obj[key] = value; // 为每个 key 赋值相同的 value
});
});
// month_31.forEach(month => obj[month] = 31)
// month_30.forEach(month => obj[month] = 30)
// 2月
obj[2] = isRunYear(year) ? 29 : 28;
return obj
}
// 求整月天数
function getMonthDay(obj, key) {
const filteredKeys = Object.keys(obj)
.map(Number) // 将 key 转换为数字
.filter(k => k < key); // 只保留小于指定 key 的值
// 根据过滤后的 key,累加相应的 value
const sum = filteredKeys.reduce((acc, currKey) => acc + Number(obj[currKey]), 0);
return sum;
}
function main(dateStr) {
// 参数检查
let error = verifyDate(dateStr)
if (error) {
alert(error)
return
}
let resCount = 0
const [year, month, day] = dateStr.split("-").map(Number)
let DayMap = getDayMap(year) // 获取当年月份对应天数
resCount += getMonthDay(DayMap, month)
resCount += day
return resCount
}