1、处理时间格式的工具类
定义一个时间格式相关的类,这个时间格式可以直接静态调用两个方法,一个是转换为两位数的时间格式(toTwoDigit),另一个是将时间转为目标的时间格式(format),里面的访问对应时间的方法定义为 get 方法,方便直接使用时返回结果
class DateFormat {
// 转为两位数格式的,如3 ->03, 9 -> -9 也可以用padStart
static toTwoDigit (num) {
return num < 10 ? `0${num}` : `${num}`
}
// 根据传入的格式来返回结果,静态方法,如:hh-mm-ss
static format (time, formation) {
return new DateFormat(time).format(formation)
}
// 构造函数,Date|number
constructor (time) {
if (typeof time === 'number') {
this.date = new Date(time)
} else {
this.date = time
}
}
// format,根据格式要求进行格式化
format (formation) {
const _this = this
return ("" + formation).replace(
/Y+|M+|D+|d+|H+|h+|m+|s+/g,
($0) => {
const res = _this[$0]
return res === undefined ? $0 : res
}
)
}
// 获取FullYear的后两位
get YY () {
return this.YYYY.toString().slice(2)
}
// 四位的年份
get YYYY () {
return this.date.getFullYear()
}
// 默认的月份
get M () {
return this.date.getMonth() + 1
}
// 两位补零的月份
get MM () {
return DateFormat.toTwoDigit(this.M)
}
// 默认的日期
get D () {
return this.date.getDate()
}
// 默认的日期 ,D,d是一样的,按照标准是d,这里为了方便通用,下面dd,DD同理
get d () {
return this.date.getDate()
}
// 补零的日期
get DD () {
return DateFormat.toTwoDigit(this.D)
}
// 补零的日期
get dd () {
return DateFormat.toTwoDigit(this.D)
}
// 获取默认小时 24小时制
get H () {
return this.date.getHours()
}
// 获取两位补零的小时, 24小时制
get HH () {
return DateFormat.toTwoDigit(this.H)
}
// 获取默认的小时 12小时
get h () {
const h = this.H
return h > 12 ? h - 12 : h
}
// 两位补零的小时 12小时制
get hh () {
return DateFormat.toTwoDigit(this.h)
}
// 默认的分钟
get m () {
return this.date.getMinutes()
}
// 两位补零的分钟
get mm () {
return DateFormat.toTwoDigit(this.m)
}
// 默认的秒钟
get s () {
return this.date.getSeconds()
}
// 两位补零的秒钟
get ss () {
return DateFormat.toTwoDigit(this.s)
}
}
例子:
// 静态方法直接调用
DateFormat.format(Date.now(), 'YY-MM-DD HH.mm.ss') // '22-01-09 23.10.43'
// 实例化以后调用
let dd = new DateFormat(Date.now())
dd.YYYY // 2022
dd.hh // 11
dd.HH // 23
dd.format('YYYY--MM--DD&&&HH:mm:ss') // '2022--01--09&&&23:11:53'
2、毫秒数转为剩余时间,天,时,秒
function transfromToLeftTime(time) {
if (!time) {
return
}
// 毫秒转为秒
let left = time / 1000
left = Math.max(left, 0)
// 计算剩余多少天
let days = Math.floor(left / 60 / 60 / 24)
// 计算除去天还剩余多少小时
let hours = Math.floor((left / 60 / 60) % 24)
// 除去小时还剩多少分钟
let minutes = Math.floor((left / 60) % 60)
// 余下多少秒
let seconds = Math.floor(left % 60)
return `剩余${days}天,${hours}时,${minutes}分,${seconds}秒`
}