You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular实现仅在当前时间戳5分钟后显示记录的问题

实现仅显示当前时间5分钟后的记录

需求与现有代码

我希望仅当记录的时间戳比当前时间晚5分钟时,才显示该记录。以下是我的实现代码:

HTML代码

<div *ngFor="let bookings of newBookings" class="card  mb-4">
    <div *ngIf="isTimestampAfterCurrent(bookings?.currentTimeStamp)" class="card-body">
        ....
    </div>
</div>

Component.ts代码

isTimestampAfterCurrent(timestamp: string): boolean {
    if (!timestamp) {
        // 如果没有时间戳,就显示该记录
        return true;
    }
  
    const currentTimestamp = moment(); // 获取当前时间
    const bookingTimestamp = moment(timestamp, 'YYYY-MM-DD HH:mm:ss');
    console.log(bookingTimestamp);
    return bookingTimestamp.isAfter(currentTimestamp.add(5, 'minutes'));
}

注:currentTimeStamp的格式为2023-06-25 02:29:49

问题分析

现有代码存在一个隐性bug:Moment.js的add()方法会直接修改原时间对象。调用currentTimestamp.add(5, 'minutes')后,currentTimestamp本身会变成当前时间加5分钟的结果,后续再调用这个方法时,判断基准会持续偏移,导致逻辑错误。

修复方案

修改判断逻辑,通过clone()复制当前时间对象后再添加分钟数,避免修改原基准时间:

isTimestampAfterCurrent(timestamp: string): boolean {
    if (!timestamp) {
        // 如果没有时间戳,就显示该记录
        return true;
    }
  
    const currentTimestamp = moment(); // 获取当前时间
    const bookingTimestamp = moment(timestamp, 'YYYY-MM-DD HH:mm:ss');
    // 复制当前时间后再加5分钟,保证基准时间不被修改
    const currentPlus5Minutes = currentTimestamp.clone().add(5, 'minutes');
    console.log(bookingTimestamp, currentPlus5Minutes);
    return bookingTimestamp.isAfter(currentPlus5Minutes);
}

额外优化建议

  • 若newBookings数据量较大,建议在数据获取阶段就过滤掉不符合条件的记录,减少模板层的判断逻辑,提升渲染性能。
  • 如果需要页面实时更新显示状态,可以结合Angular的AsyncPipe和定时器Observable,每隔1分钟重新执行一次时间判断。

内容的提问来源于stack exchange,提问作者Calvin Care

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 17:34:59