/**
* 时间日期转换
* @param date 当前时间,new Date() 格式
* @param format 需要转换的时间格式字符串
* @returns 返回拼接后的时间字符串
*/
export function formatDate(date: Date, format: string): string {
const week: { [key: string]: string } = {
'0': '日', '1': '一', '2': '二', '3': '三', '4': '四', '5': '五', '6': '六',
};
const quarter: { [key: string]: string } = { '1': '一', '2': '二', '3': '三', '4': '四' };
const we = date.getDay(); // 星期
const z = getWeek(date); // 周
const qut = Math.floor((date.getMonth() + 3) / 3).toString(); // 季度
const opt: { [key: string]: string } = {
'Y+': date.getFullYear().toString(),
'm+': (date.getMonth() + 1).toString(),
'd+': date.getDate().toString(),
'H+': date.getHours().toString(),
'M+': date.getMinutes().toString(),
'S+': date.getSeconds().toString(),
'q+': quarter[qut], // 季度
};
// 处理格式中的特殊标记
format = format.replace(/(W+)/, (match) => match.length > 1 ? `周${week[we]}` : week[we]);
format = format.replace(/(Q+)/, (match) => match.length === 4 ? `第${quarter[qut]}季度` : quarter[qut]);
format = format.replace(/(Z+)/, (match) => match.length === 3 ? `第${z}周` : `${z}`);
// 替换日期格式中的部分
Object.keys(opt).forEach((key) => {
const reg = new RegExp(`(${key})`);
format = format.replace(reg, (match) => match.length === 1 ? opt[key] : opt[key].padStart(match.length, '0'));
});
return format;
}
/**
* 获取当前日期是第几周
* @param dateTime 当前传入的日期值
* @returns 返回第几周数字值
*/
export function getWeek(dateTime: Date): number {
const temptTime = new Date(dateTime);
const weekday = temptTime.getDay() || 7; // 周几 (0-6,0代表星期天)
// 调整日期到上周一
temptTime.setDate(temptTime.getDate() - weekday + 1);
const firstDay = new Date(temptTime.getFullYear(), 0, 1);
// 获取第一周的第一天
const dayOfWeek = firstDay.getDay();
const spendDay = dayOfWeek === 0 ? 7 : 7 - dayOfWeek + 1;
// 计算周数
const startOfYear = new Date(temptTime.getFullYear(), 0, 1 + spendDay);
const days = Math.ceil((temptTime.getTime() - startOfYear.getTime()) / 86400000);
return Math.ceil(days / 7);
}
/**
* 将时间转换为 `几秒前`、`几分钟前`、`几小时前`、`几天前`
* @param param 当前时间,new Date() 格式或
前端TS 时间格式化函数
于 2025-01-18 09:12:04 首次发布