记录时间计算bug getDay()的一个坑

最近在使用时间计算展示当天所在这一周的数据 不免要获取当前时间所在周

javascript 复制代码
// 时间格式整理函数
function formatDate(date) {
  const year = date.value.getFullYear(),
    month = String(date.value.getMonth() + 1).padStart(2, '0'),
    day = String(date.value.getDate()).padStart(2, '0');

  return `${year}-${month}-${day}`;
}

const currentDate = ref(new Date()),
  currentDay = ref(currentDate.value.getDay()),
  startDate = ref(new Date(currentDate.value.getFullYear(), currentDate.value.getMonth(), currentDate.value.getDate() - currentDay.value + 1)),
  endDate = ref(new Date(currentDate.value.getF

const startTime = formatDate(startDate),
  endTime = formatDate(endDate);

let timeList = {
  startTime,
  endTime
};

console.log(timeList);

这里计算周一到周六 并展示均为正常 但计算周日时 会将时间退后一天

timeList跳转到下一周的周一到周日

问题出现在 currentDate.value.getDay() 这一行。getDay() 方法返回的是当前日期是星期几,其中星期日对应的值是 0,星期一是 1,以此类推。因此,使用 getDay() 方法获取到的是星期几的值。对 getDate() 方法和 getDay() 方法的处理进行调整

对源代码进行修改

javascript 复制代码
// 时间格式整理函数
function formatDate(date) {
  const year = date.getFullYear(),
    month = String(date.getMonth() + 1).padStart(2, '0'),
    day = String(date.getDate()).padStart(2, '0');

  return `${year}-${month}-${day}`;
}

const currentDate = ref(new Date()),
  currentDay = ref(currentDate.value.getDay()),
  startDate = ref(new Date(currentDate.value.getFullYear(), currentDate.value.getMonth(), currentDate.value.getDate() - (currentDay.value === 0 ? 6 : currentDay.value - 1))),
  endDate = ref(new Date(currentDate.value.getFullYear(), currentDate.value.getMonth(), currentDate.value.getDate()));

const startTime = formatDate(startDate.value),
  endTime = formatDate(endDate.value);

let timeList = {
  startTime,
  endTime
};

console.log(timeList);

在修正后的代码中,计算startDate时 通过 currentDay.value === 0 判断当前是否为星期天,

如果在正常周一到周六 比如当前天数为7月29 周六

currentDate为29 currentDay.value 为6 计算startDate时29-6+1 周一为24

当天为7月30 周日时 currentDay.value 为 0 这是getDay()设计的 周日时设为0 我们无法更改

仍按以前计算 30-0+1 自然会报错 这时跳转到下一周了 计算的周一为31 实际24

当 currentDay.value为0 时 即30时 让其 -6 而不是+1 这样30-0-6 计算的周一就能对应24

简单的数学题 其实代码实现的往往就是简单的数字逻辑

聊记一笔

相关推荐
你怎么知道我是队长2 小时前
JavaScript的变量和数据类型介绍
开发语言·javascript·ecmascript
名字还没想好☜3 小时前
Next.js 中间件实战:鉴权、重定向与 A/B 分流
开发语言·前端·javascript·中间件·react·next.js
广州灵眸科技有限公司3 小时前
瑞芯微RV1126B开发板(EASY-EAI-PI2) INI文件操作
java·前端·javascript·网络·人工智能
心中有国也有家4 小时前
AtomGit Flutter 鸿蒙客户端:ModalBottomSheet 实战
android·javascript·学习·flutter·华为·harmonyos
仙人球部落6 小时前
-python-LangGraph框架(3-31-LangGraph 「合并式状态管理」的原理与实践)
开发语言·javascript·python
sunfdf7 小时前
Next.js 新手从零部署到首跑实战指南
开发语言·javascript·ecmascript
SmartBoyW7 小时前
前端死磕:一文彻底搞懂 JS 事件循环 (Event Loop) 与宏微任务
前端·javascript
mONESY8 小时前
基于MCP协议搭建全链路智能Agent:地图检索+浏览器自动化+本地文件操控实战
javascript
研☆香8 小时前
闭包实战避坑指南
javascript
你怎么知道我是队长9 小时前
JavaScript 的控制语句介绍
开发语言·javascript·ecmascript