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