js获取前一天时间

358 阅读2分钟

偶然再一次工作中,产品出了一个需求,筛选条件默认日期为前一天,因为我是第一次做这种需求,所以就是通过得到当前的日期,然后日-1,得到前一天的时间

downloadTransportLimitation(type){ 
  const newDate = new Date(); // 获得当前的时间 
  const year = newDate.getFullYear(); // 获取当前年份
  const month = newDate.getMonth() + 1; // 获取当前⽉份(0-11,0代表1⽉所以要加1); 
  const day = newDate.getDate() - 1;// 获取当前⽇(1-31) 
  const beginTime = year+ "-" + "0" + month + "-" + day + " 00:00:00" // 赋值 
  const endTime = year+ "-" + "0" + month + "-" + day + " 23:59:59" // 赋值 
  // 走接口 
  if(type == '区域报表'){officeReportDownload({beginTime,endTime}).then(res=>{this.downLoadimg(res)})} 
  if(type == '业务中心'){businessReportDownload({beginTime,endTime}).then(res=>{this.downLoadimg(res)})} 
  if(type == '线路运输'){lineTransportLimitationReportDownload({beginTime,endTime}).then(res=>{this.downLoadimg(res)})} 
}

月底写的,测试没问题,到了下个月初,说我的线上出了问题,后端同学就找到了我说给他传两个2022-6-0,我一想不对,这样写有问题,后来就想到了操作时间戳,先是知道一天有多少毫秒,然后在拿当前的时间戳减去一天的毫秒,就能得到前一天的时间。

downloadTransportLimitation(type){ 
    const newDate = new Date().getTime() // 获得当前的时间 
    const date = newDate - 24*60*60*1000; // 通过转换时间戳减一天 
    const oldDay = new Date(date) // 将减好的时间戳转换为Date对象的时间戳 
    const year = oldDay.getFullYear(); // 获取当前年份 
    const month = oldDay.getMonth() + 1; // 获取当前⽉份(0-11,0代表1⽉所以要加1); 
    const day = oldDay.getDate();// 获取当前⽇(1-31) 
    const beginTime = year+ "-" + "0" + month + "-" + day + " 00:00:00" // 赋值 
    const endTime = year+ "-" + "0" + month + "-" + day + " 23:59:59" // 赋值 
    // 走接口 
    if(type == '区域报表'){officeReportDownload({beginTime,endTime}).then(res=>{this.downLoadimg(res)})} 
    if(type == '业务中心'){businessReportDownload({beginTime,endTime}).then(res=>{this.downLoadimg(res)})} 
    if(type == '线路运输'){lineTransportLimitationReportDownload({beginTime,endTime}).then(res=>{this.downLoadimg(res)})} 
}

有的时候思路确实不对,当解决不了问题的时候,不妨换个思路。

加油!前端人