/** * 时间相关方法 * 字符 含义 举例 * 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 */ export class TimeHelper { private constructor() { } /** * 获取当前时间戳 * @returns */ static getTimeMillis() { return new Date().getTime() } /** * 获取当前时间,指定返回样式 * @param formats 时间格式 * 'yyyy-MM-dd HH:mm:ss' */ static getTime(format: string = 'yyyy-MM-dd HH:mm:ss') { return TimeHelper.formatDate(new Date(), format) } /** * 时间格式化 * @param date number类型为毫秒级时间戳 * @param format * @returns */ static formatDate(date: Date | number, format: string = 'yyyy-MM-dd HH:mm:ss') { 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]); } } // // 时间戳转指定类型字符串(毫秒级) // static formatDateForTime(time: number, format: string) { // return this.formatDate(new Date(time), format); // } /** * 获取月份天数 * @param year * @param month * @returns */ static getMonthDays(year: number, month: number) { return new Date(year, month, 0).getDate() } }