学无先后,达者为师

网站首页 编程语言 正文

将字符串转换成时间戳,yyyymmss到yyyy-mm-dd ,之后从时间戳转换成时间格式字符串

作者:沙漠蓝色披头 更新时间: 2022-01-17 编程语言

按天算

     let commonForDay = 20210115

      if (this.newFtpConfig.fileNameAddRule === '1') {//按天
        var dateString = commonForDay;
        var pattern = /(\d{4})(\d{2})(\d{2})/;
        var formatedDate = dateString.replace(pattern, '$1-$2-$3');
        var date = new Date(formatedDate);
        var values = date.valueOf();//将时间转换成时间戳
        var totalValues = values + 24 * 60 * 60 * 1000 //生成最终的时间戳
        var date1 = new Date(totalValues)
        let times = this.formatDate(date1, 'yyyy-MM-dd')//按照格式转换成时间字符串
        let theLastTime = times.split('-').join('')//去除‘-’并生成新的字符串
        this.newFtpConfig.nextFileName = theLastTime

      } else if (this.newFtpConfig.fileNameAddRule === '2') {//按周

        var endForWeek = commonForDay.substr(4, 2)
        if (endForWeek < '52') {
          var intValue = parseInt(endForWeek)
          var lastValue = intValue + 1
          if (lastValue < 10) {
            lastValue = '0' + lastValue
          }
          this.newFtpConfig.nextFileName = startForDay + lastValue
        }else if (endForWeek === '52') {
         var childweek = commonForDay.substr(0,4)
         var lastweek = parseInt(childweek) + 1
          this.newFtpConfig.nextFileName = lastweek + '01'
        }

      }
      
    formatDate (date, fmt) {
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
      }
      let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
      };

      // 遍历这个对象
      for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
          // console.log(`${k}`)
          console.log(RegExp.$1)
          let str = o[k] + '';
          fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str));

        }
      }
      function padLeftZero (str) {
        return ('00' + str).substr(str.length);
      }
      return fmt;
    },


另一种实现:

var dateTime = new Date('2021-02-28')
dateTime = dateTime.setDate(dateTime.getDate()+1)
dateTime = new Date(dateTime);
console.log(dateTime.toLocaleDateString())

原文链接:https://blog.csdn.net/u013075460/article/details/119615046

栏目分类
最近更新