Angular 8中计算当前日期与API返回日期的天数差,是否用Moment?
在Angular 8中计算日期差值:是否该用Moment?
嘿,我来帮你梳理下这个问题~
首先明确说:Moment.js现在已经进入维护模式了,官方不再添加新功能,只做必要的bug修复,所以如果是新项目,我更推荐用原生的Date API或者更轻量、更现代化的库比如date-fns。不过如果你的项目已经在使用Moment,继续用它也完全没问题,毕竟它的API确实顺手好懂。
接下来给你几种可行的实现方案,适配你在ngFor里计算日期差的需求:
方案1:用原生Date API实现(推荐新项目)
你可以在组件里写一个计算天数差的方法,然后在模板的ngFor中直接调用:
组件代码
// 在你的组件类中添加这个方法 calculateDaysDifference(dateString: string): number { const apiDate = new Date(dateString); const currentDate = new Date(); // 计算时间差(毫秒),转换为天数 const timeDiff = Math.abs(currentDate.getTime() - apiDate.getTime()); // 用ceil确保不满一天也按一天算,你也可以根据需求换成floor或round const dayDiff = Math.ceil(timeDiff / (1000 * 60 * 60 * 24)); return dayDiff; }
模板代码
<div *ngFor="let message of apiMessages"> 消息发送日期:{{ message.sendDate }} | 已过去 {{ calculateDaysDifference(message.sendDate) }} 天 </div>
方案2:用Moment.js实现(适合已有依赖的项目)
如果你的项目已经引入了Moment,那用它来计算会更简洁:
首先确保已经安装Moment:
npm install moment --save
组件代码
import * as moment from 'moment'; // 组件类中的计算方法 calculateDaysWithMoment(dateString: string): number { const apiDate = moment(dateString); const currentDate = moment(); // 直接获取天数差值,Moment会帮你处理时区、格式这些细节 return currentDate.diff(apiDate, 'days'); }
模板代码
和方案1类似,直接在ngFor里调用这个方法就行。
更优实践:用Angular自定义管道
在模板里直接调用方法有个小问题:Angular的变更检测会频繁触发这个方法,可能影响性能。更符合Angular最佳实践的方式是写一个自定义纯管道,它只会在输入值变化时重新计算:
首先生成管道:
ng generate pipe dayDifference
管道代码
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'dayDifference' }) export class DayDifferencePipe implements PipeTransform { transform(dateString: string): number { const apiDate = new Date(dateString); const currentDate = new Date(); const timeDiff = Math.abs(currentDate.getTime() - apiDate.getTime()); return Math.ceil(timeDiff / (1000 * 60 * 60 * 24)); } }
模板代码
<div *ngFor="let message of apiMessages"> 消息发送日期:{{ message.sendDate }} | 已过去 {{ message.sendDate | dayDifference }} 天 </div>
这样不仅代码更整洁,性能也更好~
内容的提问来源于stack exchange,提问作者web developer
相关产品推荐
相关产品推荐

