js ts最美时间格式化,解析:今天 昨天 周一,周二。。。。。。

/**
 * 时间格式化
 * @param inputDateStr 时间字符串 列如:"2024-05-16 22:28:15"
 * @return 两天内返回 昨天 22:28 今天:22:28,三天以上七天以内返回:周(1,2,3,4,5,6,7) 22:28 ,如果是更久以前则返回 05-16 22:28
 */
export function formatDate(inputDateStr: string): string {
    // 解析输入的日期字符串
    const inputDate = new Date(inputDateStr);
    if (isNaN(inputDate.getTime())) {
        throw new Error("Invalid date string");
    }

    // 获取当前日期和时间
    const now = new Date();

    // 去掉时间部分,只保留日期
    const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
    const inputDay = new Date(inputDate.getFullYear(), inputDate.getMonth(), inputDate.getDate());

    // 计算时间差(以毫秒为单位)
    const timeDiff = today.getTime() - inputDay.getTime();
    const dayDiff = timeDiff / (1000 * 60 * 60 * 24);

    // 获取输入日期的小时和分钟
    const hours = inputDate.getHours().toString().padStart(2, '0');
    const minutes = inputDate.getMinutes().toString().padStart(2, '0');
    const timePart = `${hours}:${minutes}`;

    if (dayDiff < 0) {
        // 输入日期在今天之后,不做处理
        throw new Error("Input date is in the future");
    } else if (dayDiff === 0) {
        // 今天
        return `今天 ${timePart}`;
    } else if (dayDiff === 1) {
        // 昨天
        return `昨天 ${timePart}`;
    } else if (dayDiff <= 7) {
        // 一周内
        const weekDays = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
        const dayOfWeek = weekDays[inputDay.getDay()];
        return `${dayOfWeek} ${timePart}`;
    } else {
        // 更久以前
        const month = (inputDate.getMonth() + 1).toString().padStart(2, '0');
        const day = inputDate.getDate().toString().padStart(2, '0');
        return `更久以前:${month}-${day} ${timePart}`;
    }
}

posted @ 2024-05-17 07:48  Amani_Bey  阅读(2)  评论(0编辑  收藏  举报