js格式化日期

103 篇文章 0 订阅
97 篇文章 0 订阅
<script>
  
  // 不足10位补零
  function addZero (val){
    val = Number(val)
    return val < 10 ? '0' + val : val
  }

  // 时间
  let time = '2019-5-30 12:0:0'

  // 基于日期 格式化时间字符串
  function formatTime(time) {
    time = time.replace(/-/g,'/')
    time = new Date(time)

    let year = time.getFullYear(),
        month = addZero(time.getMonth() + 1),
        day = addZero(time.getDate()),
        hours = addZero(time.getHours()),
        minutes = addZero(time.getMinutes()),
        seconds = addZero(time.getSeconds())

    return  year + '年' + 
            month + '月' + 
            day + '日 ' + 
            hours + ':' + 
            minutes + ':' + 
            seconds 
  }

  time = formatTime(time)
  console.log(time)

  // 基于字符串 格式时间
  function formatTime(time){
    let ary = time.split(' '),
        aryLeft = ary[0].split('-'),
        aryRight = ary[1].split(':')
    
    ary = aryLeft.concat(aryRight)

    let result =  ary[0] + '年' + 
                  addZero(ary[1]) + '月' + 
                  addZero(ary[2]) + '日' + 
                  ' ' + 
                  addZero(ary[3]) + ':' + 
                  addZero(ary[4]) + ':' + 
                  addZero(ary[5])

    return result
  }

  time = formatTime(time)
  console.log(time)
</script>


//万能格式化日期方法
<script>

  String.prototype.formatTime = function formatTime(template) {
    // 初始模板
    typeof template === 'undefined' ? template = "{0}年{1}月{2}日 {3}:{4}:{5}" : null

    let matchAry = this.match(/\d+/g)

    template = template.replace(/\{(\d+)\}/g,(x, y) => {
      let val = matchAry[y] || '00'
      val.length < 2 ? val = '0' + val : null
      return val
    })

    return template
  }

  let time = '2019-5-30 12:0:0'

  console.log(time.formatTime("{1}-{2} {3}:{4}"))

</script>
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值