对时间日期格式化

首先调用这个函数的时候,第一个参数需要传入需要格式化的时间戳。

如果要得到制定的日期类型,还要传入的type类型,来对日期进行格式化,得到想要的日期格式。

formaterDate(cellValue, type) {
    // cellValue为传入的需要格式化的时间戳,type为传入的需要格式化得到的日期类型
  if (cellValue == null || cellValue === '') {
    // 如果没有传入了需要格式化的时间戳
    return ''
  } else {
    // 如果传入了需要格式化的日期值:cellValue
    var date = new Date(cellValue)

    // 年
    var year = date.getFullYear()

    // 月
    var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1

    // 日
    var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()

    // 时
    var hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()

    // 分

    var minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()

    // 秒
    var seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()

 
    if (type === 'year') {

      // 如果需要格式化,得到年份
      return year
    } else if (type === 'month') {

      // 如果需要格式化,得到月份
      return month
    } else if (type === 'date') {

      // 如果需要格式化,得到年月日
      return year + '-' + month + '-' + day
    } else if (type === 'hours') {

      // 如果只需要格式化,得到小时
      return hours + ':00'
    } else if (type === 'HMS') {

       // 如果只需要格式化,得到时分秒
      var hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
      var minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
      var seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
      return hours + ':' + minutes + ':' + seconds
    } else if (type === 'seconds') {

      // 如果需要格式化,得到年月日时分
      return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes
    } else {

      // 如果只需要格式化,得到年月日时分秒
      return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds
    }
  }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值