前端时间字符串化处理

因为前端显示的时间格式,有些地方需要完整的时间,有些地方只需要显示时刻等简短的时间;有些时间需要本地化处理后再进行上面的完整或简短的时间字符串化处理;且时间处理一般系统都会用到,所以记录一下代码

class TimeString {
  constructor(time) {
    this._time = new Date(time)
  }
  doubleString(num) {
    // 或者另一种写法: (Array(2).join(0) + num).slice(-2)
    let str = `${num}`
    if (num < 10) {
      str = `0${num}`
    }
    return str
  }
  threeString(num) {
    // 或者另一种写法: (Array(3).join(0) + num).slice(-2)
    let str = `${num}`
    if (num < 100) {
      if (num < 10) {
        str = `00${num}`
      } else {
        str = `0${num}`
      }
    }
    return str
  }
  get time() {
    return this._time
  }
  get fullYear() {
    return this._time.getFullYear()
  }
  get month() {
    return this.doubleString(this._time.getMonth() + 1)
  }
  get date() {
    return this.doubleString(this._time.getDate())
  }
  get hour() {
    return this.doubleString(this._time.getHours())
  }
  get minute() {
    return this.doubleString(this._time.getMinutes())
  }
  get second() {
    return this.doubleString(this._time.getSeconds())
  }
  get millSecond() {
    return this.threeString(this._time.getMilliseconds())
  }
  get fullTime() {
    return `${this.fullYear}-${this.month}-${this.date} ${this.hour}:${this.minute}:${this.second}.${this.millSecond}`
  }
  get monthSecond() {
    return `${this.month}-${this.date} ${this.hour}:${this.minute}:${this.second}`
  }
  get hourSecond() {
    return `${this.hour}:${this.minute}:${this.second}`
  }
}
// utc时间处理
class UtcTimeString extends TimeString {
  constructor(time) {
    super(time)
    const offMin = new Date().getTimezoneOffset()
    this._time = new Date(time - offMin * 60 * 1000)
  }
}

使用的时候

const timeObj = new UtcTimeString('时间变量')
const fullTime = timeObj.fullTime
console.log(fullTime)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值