【JS】判断一个日期是当年的第几天

前言

现有一个日期字符串,如: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
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

田本初

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值