随手记:js查询过去XX天前日期和未来XX天后日期

文章介绍了如何使用JavaScript函数getDateBeforeThreeDays(),根据给定的日期和天数(可为未来或过去),计算并返回新的日期。同时展示了如何结合服务器时间进行日期操作。
摘要由CSDN通过智能技术生成
    // 获取XX日期xx天是什么时候
    // whichDay: 日期
    // num: 天数
    // future: 是否是未来
    getDateBeforeThreeDays(whichDay,num, future) {      
      let date = new Date(whichDay); 
      if(future) {
        date.setDate(date.getDate() + num);
      }else{
        date.setDate(date.getDate() - num);
      }   
      let year = date.getFullYear();      
      let month = (date.getMonth() + 1) < 10 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1);      
      let day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();      
      let result = year + '-' + month + '-' + day;    
      if(future) {
        console.log(whichDay,num,'天后是', result)
      }else{
        console.log(whichDay,'前',num,'天是', result)
      } 
      return result;
    },

需求:
需要计算当前日期的前15天后15天,封装方法,需要前多少天后多少天可以传参实现

例子:

    this.getDateBeforeThreeDays('2024-03-29 17:00:00', 3);
    //2024-03-29 17:00:00 前 3 天是 2024-03-26
    this.getDateBeforeThreeDays('2024-03-28', 3);
    //2024-03-28 前 3 天是 2024-03-25


    // 获取当前服务器时间
    getServerDate().then(res => {
      console.log('服务器时间', res)
      this.getDateBeforeThreeDays(res.data.nowDate, 3);
       //2024-04-28 18:09:53 前 3 天是 2024-04-25
      this.getDateBeforeThreeDays(res.data.nowDate, 7, true);
      //2024-04-28 18:09:53 7 天后是 2024-05-05
    })


 

  • 11
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

peachSoda7

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

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

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

打赏作者

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

抵扣说明:

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

余额充值