相信大家在开发过程中,经常会需要用到各种的日期格式,如‘2020-05-07’、‘2020年5月7日’、‘2020年5月7日 15:52:47’等等的日期格式要求,不知道大家都写过多少遍的转日期格式的方法了,反正天某是写烦了,于是就产生了想要封装一个工具出来的想法。
export class Tools{
/**
* @param timestamp 时间戳 ms
* @param formats 时间格式 Y M D h m s
* */
public static getDate(timestamp:number, formats: string = 'Y-M-D'):string {
let date = timestamp ? new Date(timestamp) : new Date();
let year = date.getFullYear();
let month = this.add0(date.getMonth() + 1);
let day = this.add0(date.getDate());
let hour = this.add0(date.getHours());
let minute = this.add0(date.getMinutes());
let second = this.add0(date.getSeconds());
// 将传入的时间格式分别替换成相应的年月日时分秒,而且里面的时分秒对应的字符大家也可以自己定义哈
return formats.replace(/Y|M|D|h|m|s/ig, function (matches:string) {
let result: any = {
Y : year,
M : month,
D : day,
h : hour,
m : minute,
s : second
};
return result[matches];
})
}
/**
* @param value 传入值
* */
private static add0(value:string|number):string {
value = Number(value)
return value < 10 ? '0' + value : value + ''
}
}
相信大家看了上面的代码也很直观了,那么调用方法呢,我也简单说一下
// 这样一来大家就可以随心所欲的定制自己想要的日期格式了
Tools.getDate(1593763401747, 'Y-M-D h:m:s') Tools.getDate(1593763401747, 'Y年M月D日 h:m')
如果有好的建议或者发现天某哪里有错误的,欢迎大家指出哟