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}`;
    }
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值