记录时间计算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

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

聊记一笔

相关推荐
杨过姑父7 分钟前
部署开源版禅道,修改apache端口无效解决
bug·apache·软件工程·issue
前端Hardy21 分钟前
HTML&CSS:3D图片切换效果
前端·javascript
spionbo42 分钟前
Vue 表情包输入组件实现代码及完整开发流程解析
前端·javascript·面试
全宝42 分钟前
✏️Canvas实现环形文字
前端·javascript·canvas
前端梭哈攻城狮1 小时前
uniapp图片上传添加水印/压缩/剪裁
前端·javascript·vue.js
天涯学馆1 小时前
前后端分离的 API 设计:技术深度剖析
前端·javascript·面试
爱编程的喵1 小时前
深入理解JavaScript原型机制:从Java到JS的面向对象编程之路
java·前端·javascript
独立开阀者_FwtCoder1 小时前
Cursor 1.0 重磅发来袭(毛骨悚然,开始学习你如何编码)
前端·javascript·github
五点六六六1 小时前
一些关于TreeShaking的AST的理解
前端·javascript·前端工程化
海盐泡泡龟2 小时前
“组件、路由懒加载”,在 Vue3 和 React 中分别如何实现? (copy)
前端·javascript·react.js