当前位置: 首页 > news >正文

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

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

// 时间格式整理函数
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.getFconst startTime = formatDate(startDate),endTime = formatDate(endDate);let timeList = {startTime,endTime
};console.log(timeList);

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

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

对源代码进行修改

// 时间格式整理函数
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
简单的数学题 其实代码实现的往往就是简单的数字逻辑
聊记一笔

http://www.lryc.cn/news/103623.html

相关文章:

  • 【lesson5】linux vim介绍及使用
  • 【玩转Linux】Linux输入子系统简介
  • grid map学习笔记2之grid map的一些常规定义和功能包说明
  • Python-文件操作
  • windows中注册redis服务启动时报1067错误
  • 大数据面试题:HBase的RegionServer宕机以后怎么恢复的?
  • ansible的脚本——playbook剧本
  • 【系统监控程序】
  • 计算机论文中名词翻译和解释笔记
  • 读书笔记-《ON JAVA 中文版》-摘要20[第十九章 类型信息-1]
  • 3、Linux驱动开发:模块_传递参数
  • 基于 ThinkPHP 5.1(稳定版本) 开发wms 进销存系统源码
  • 全面解析 SOCKS5 代理和 HTTP 代理在网络安全与爬虫应用中的技术对比与应用指南
  • DevOps系列文章 之 docker 制作kafka镜像
  • iPhone 安装 iOS 17公测版(Public Beta)
  • Spingboot yaml 配置文件及数据读取
  • vue中使用axios发送请求时,后端同一个session获取不到值
  • html请求谷歌音频跨域问题(谷歌翻译接口)虚拟机ping不通google(下载谷歌音频、下载百度翻译音频)
  • 【设计模式|结构型】享元模式(Flyweight Pattern)
  • 最小覆盖子串(JS)
  • <C语言> 预处理和宏
  • 代驾公司如何进行运营分析
  • 初学HTML:采用CSS绘制一幅夏天的图
  • 经典文献阅读之--NoPe-NeRF(优化无位姿先验的神经辐射场)
  • 在docker中没有vi如何修改docker中的文件
  • 【Docker】Docker应用部署之Docekr容器安装Nginx
  • flutter开发实战-jsontodart及 生成Dart Model类
  • C++复刻:[流光按钮]+[悬浮波纹按钮]
  • CompletableFuture 详解
  • el-table数据处理