2024-10-28 19:45:05 +08:00
|
|
|
|
/**
|
|
|
|
|
|
* 时间相关方法
|
|
|
|
|
|
* 字符 含义 举例
|
|
|
|
|
|
* y(小写y) 年 yyyy-2015
|
|
|
|
|
|
* M(大写M) 月 MM-01
|
|
|
|
|
|
* d(小写d) 日(某月份对应的天数) dd-02
|
|
|
|
|
|
* H(24 小时制,大写H) 小时(0-23) HH-17
|
|
|
|
|
|
* h(12 小时制,小写h) 小时(1-12) hh-05
|
|
|
|
|
|
* m(小写m) 分钟 mm-19
|
|
|
|
|
|
* s(小写s) 秒 ss-22
|
|
|
|
|
|
* Y(大写y) Week Year YYYY-2015
|
|
|
|
|
|
* D(大写D) 一年中的天数(年份为大写Y起作用) DD-362
|
|
|
|
|
|
* S(大写S) 毫秒 SSS-043
|
|
|
|
|
|
*/
|
2024-10-29 19:07:32 +08:00
|
|
|
|
|
2024-10-28 19:45:05 +08:00
|
|
|
|
export class TimeHelper {
|
2024-10-31 12:28:44 +08:00
|
|
|
|
private constructor() {
|
|
|
|
|
|
}
|
2024-11-07 10:14:39 +08:00
|
|
|
|
|
2024-10-28 19:45:05 +08:00
|
|
|
|
/**
|
|
|
|
|
|
* 获取当前时间戳
|
|
|
|
|
|
* @returns
|
|
|
|
|
|
*/
|
|
|
|
|
|
static getTimeMillis() {
|
|
|
|
|
|
return new Date().getTime()
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
|
* 获取当前时间,指定返回样式
|
|
|
|
|
|
* @param formats 时间格式
|
2024-10-31 12:23:46 +08:00
|
|
|
|
* 'yyyy-MM-dd HH:mm:ss'
|
2024-10-28 19:45:05 +08:00
|
|
|
|
*/
|
2024-10-31 12:23:46 +08:00
|
|
|
|
static getTime(format: string = 'yyyy-MM-dd HH:mm:ss') {
|
2024-11-07 10:14:39 +08:00
|
|
|
|
return TimeHelper.formatDate(new Date(), format)
|
2024-10-31 12:23:46 +08:00
|
|
|
|
}
|
2024-11-07 10:14:39 +08:00
|
|
|
|
|
2025-03-11 11:03:09 +08:00
|
|
|
|
/**
|
|
|
|
|
|
* 时间格式化
|
|
|
|
|
|
* @param date number类型为毫秒级时间戳
|
|
|
|
|
|
* @param format
|
|
|
|
|
|
* @returns
|
|
|
|
|
|
*/
|
|
|
|
|
|
static formatDate(date: Date | number, format: string) {
|
|
|
|
|
|
|
|
|
|
|
|
if (typeof date === 'number') {
|
|
|
|
|
|
return this.formatDate(new Date(date), format);
|
|
|
|
|
|
} else {
|
|
|
|
|
|
const replacements: { [key: string]: string } = {
|
|
|
|
|
|
yyyy: date.getFullYear().toString(),
|
|
|
|
|
|
MM: String(date.getMonth() + 1).padStart(2, "0"),
|
|
|
|
|
|
dd: String(date.getDate()).padStart(2, "0"),
|
|
|
|
|
|
HH: String(date.getHours()).padStart(2, "0"),
|
|
|
|
|
|
mm: String(date.getMinutes()).padStart(2, "0"),
|
|
|
|
|
|
ss: String(date.getSeconds()).padStart(2, "0")
|
|
|
|
|
|
};
|
|
|
|
|
|
return format.replace(/yyyy|MM|dd|HH|mm|ss/g, matched => replacements[matched]);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2024-10-28 19:45:05 +08:00
|
|
|
|
}
|
2025-03-11 11:03:09 +08:00
|
|
|
|
|
|
|
|
|
|
// 时间戳转指定类型字符串(毫秒级)
|
2025-03-10 19:02:20 +08:00
|
|
|
|
static formatDateForTime(time: number, format: string) {
|
|
|
|
|
|
return this.formatDate(new Date(time), format);
|
|
|
|
|
|
}
|
2024-11-07 10:14:39 +08:00
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
|
* 获取月份天数
|
|
|
|
|
|
* @param year
|
|
|
|
|
|
* @param month
|
|
|
|
|
|
* @returns
|
|
|
|
|
|
*/
|
|
|
|
|
|
static getMonthDays(year: number, month: number) {
|
|
|
|
|
|
return new Date(year, month, 0).getDate()
|
|
|
|
|
|
}
|
2024-10-29 19:07:32 +08:00
|
|
|
|
}
|