JS日期转换小技巧(日期补零、日期加减)

如果你遇到后台给你的时间是时间戳的时候,虽然有很多封装好的方法供我们使用,但是,还有有些需求用不了这些封装好的方法。
所以,我总结了以下方法。

我遇到的问题是,一个类似于驾驶证颁发日期。在过期之前要复审,所谓的复审就是过期的日期那天 减去三年零一天。这个时候后台已经把过期的时间戳返给我。这个时候就需要我转换一下

代码如下

const date = new Date(this.getCard.endDate)
    
      //补零操作
      // if (date.getMonth() + 1 <= 9) {
      //   mounthDay = "0" + mounth;
      // } else {
      //   mounthDay = mounth;
      // }
      // if (date.getDate() <= 9) {
      //   dateDay = "0" + date.getDate();
      // } else {
      //   dateDay = date.getDate();
      // }
      // if (date.getHours() <= 9) {
      //   hours = "0" + date.getHours();
      // } else {
      //   hours = date.getHours();
      // }
      // if (date.getMinutes() <= 9) {
      //   minutes = "0" + date.getMinutes();
      // } else {
      //   minutes = date.getMinutes();
      // }
      // if (date.getSeconds() <= 9) {
      //   seconds = "0" + date.getSeconds();
      // } else {
      //   seconds = date.getSeconds();
      // }
      // return (
      //   date.getFullYear() +
      //   "-" +
      //   mounthDay +
      //   "-" +
      //   dateDay +
      //   " " +
      //   hours +
      //   ":" +
      //   minutes +
      //   ":" +
      //   seconds
      // );
      //年份减去三年
      let year=(date.getFullYear()-3)
      let mounthDay = 0;
      //因为月份是从0开始 所以要加1
      let mounth = date.getMonth() + 1;
      let dateDay = 0;
      //要求是减去三年零一天
      //判断如果日期是1日 那么要判断 首先月份要减一
      if(date.getDate()-1<1){
        mounth=mounth-1
        //判断如果月份是一月份 减1的时候 要规整为12月 并且年份也要再减去1
        if(mounth-1<1){
          year=year-1
          mounth=12
        }
        //这里判断如果月份为31天的时候和30天的时候
        if(mounth==1 || mounth==3 ||mounth==5||mounth==7||mounth==8||mounth==10 ||mounth==12){
          dateDay=31
        }else{
          dateDay=30
        }
      }else{
      //这里是最外层判断日期是否小于1 取反之就是不小于1的时候 正常减1就行
        dateDay=date.getDate()-1
      }
      //这里是补0操作
      if(mounth<10){
        mounth="0"+mounth
      }
      if(dateDay<10){
        dateDay="0"+dateDay
      }

总结:

date是自己的时间戳转换为中国标准时间 :date = new Date(this.getCard.endDate)
date.getFullYear() 获取的年份 //2019
date.getMonth() + 1 是获取的月份//11
date.getDate() 获取日期//01
date.getHours()获取小时 //15
date.getMinutes() 获取分钟//55
date.getSeconds() 获取秒数 //10

写的很详细了 很基础的东西 用到可以直接拿去用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值