原生JS算出三个月前的时间的时间戳

作者最近在公司的项目中又遇到了一个难题,在订单这一块需要查询三个月内的所有订单,作者是今年刚毕业的码农实习生。第一次接触这种东西。刚接到手的时候是一脸懵逼,不知道该如何做,没有一些想法,然后跑去问候了度娘,但是度娘脾气挺大的,没告诉我怎么实现的,却给我提供了一些思路。

思路:既然要获取三个月前的时间,那么获取现在的时间是很有必要的。这里利用了一个 JS Date 对象的一些知识点利用现在的时间算出了三个月前的时间。

具体如何实现作者在下面提供了一些完成的代码。各种注释可谓是一看就会的,所以接下来还是好好的读一读代码就可以理解了。作者个人因为菜,所以各路大神如果还有啥修改意见或者有另外一种解决方案欢迎在下面留言,作者会一一回复,并且会尝试各路大神的想法和思路等等,废话就不扯了,下面贴出源代码。可直接复制粘贴使用,如果有兴趣也可以研究一下,(大神请自动忽略)

getThreeMonths () {
      // let timeOne = new Date(1575158521000)
      let timeOne = new Date()
      let year = timeOne.getFullYear()
      let month = timeOne.getMonth() + 1
      let day = timeOne.getDate()
      let hours = timeOne.getHours()
      let minutes = timeOne.getMinutes()
      let seconds = timeOne.getSeconds()

      console.log(`现在的时间是:${year}-${month}-${day} ${hours}:${minutes}:${seconds}`)

      // 计算3个月后的月份
      let ThreeMonths = month - 3

      // 如果小于 0 说明是去年
      if (ThreeMonths <= 0) {
        year = year - 1
      }

      // 如果 等于 -2 说明当前月是 1 月份 所以三个月前是去年 10月
      if (ThreeMonths === -2) {
        ThreeMonths = 10
      }

      // 如果 等于 -1 说明当前月是 2 月份 所以三个月前是去年 11月
      if (ThreeMonths === -1) {
        ThreeMonths = 11
      }

      // 如果 等于 0 说明当前月是 3 月份 所以三个月前是去年 12月
      if (ThreeMonths === 0) {
        ThreeMonths = 12
      }

      // 获取当前的时间的日期字符串
      // **如果天数的值为零,则默认返回当前月份的最后一天
      let timeTow = new Date(year, ThreeMonths, 0, hours, minutes, seconds)

      // 获取三个月前的最后一天
      let ThreeMonthsDay = timeTow.getDate()

      // 获取三个月前的小时数
      let ThreeMonthsHour = timeTow.getHours() < 10 ? '0' + timeTow.getHours() : timeTow.getHours()

      // 获取三个月前的分钟数
      let ThreeMonthsMinutes = timeTow.getMinutes() < 10 ? '0' + timeTow.getMinutes() : timeTow.getMinutes()

      // 获取三个月前的秒数
      let ThreeMonthsSeconds = timeTow.getSeconds() < 10 ? '0' + timeTow.getSeconds() : timeTow.getSeconds()

      // 判断如果当前月份的天数大于三个月前的天数时,则当前天数等于三个月前的天数
      if (day > ThreeMonthsDay) {
        day = ThreeMonthsDay
      }

      day = day < 10 ? '0' + day : day

      console.log(`三个月前的时间是:${year}-${ThreeMonths}-${day} ${ThreeMonthsHour}:${ThreeMonthsMinutes}:${ThreeMonthsSeconds}`)

      // 格式化时间
      const THREE_MONTHS_AGO = `${year}/${ThreeMonths}/${day} ${ThreeMonthsHour}:${ThreeMonthsMinutes}:${ThreeMonthsSeconds}`

      // 生成时间戳
      const THREE_STAMP = new Date(THREE_MONTHS_AGO).getTime()

      return THREE_STAMP
    }

结语:在本文的最后作者也唠嗑两句,作者写的代码绝对没有抄袭或者复制别人的代码,作者写的代码都是经过自己的思考。不断的踩坑踩出来的代码。所以不存在复制别人的博客拿来就用。

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值