我有以下数据:
{
"content": [
{
"id": 15076772,
"date": "2019-06-26T15:37:36"
},
{
"id": 15074042,
"date": "2019-03-05T15:06:57"
},
{
"id": 15073812,
"date": "2019-09-17T14:32:18"
},
{
"id": 15073810,
"date": "2019-09-18T14:31:56"
}
]
}我想根据当天的日期将每个日期转换为特定的格式
如果newDate() = 2019-09-18T14: 31: 56如果newDate()不等于当天的日期而是昨天的日期,我们将在今天发布
然后,根据日期的不同,在一周的日期之后,以及在离开一周后,数据的正常日期。有点像聊天系统中显示的日期
我不知道angular是否能自动完成
我不知道angular是否可以自动完成,但我知道Moment.js可以通过日历时间完成。
如果有人能教我,那就太好了。
发布于 2019-09-18 21:07:31
Angular没有内置此功能,但您可以构建自己的管道或使用现有管道(https://github.com/AndrewPoyntz/time-ago-pipe)
不是我开发的,而是一个很好的例子:
https://github.com/AndrewPoyntz/time-ago-pipe/blob/master/time-ago.pipe.ts
如果你不介意它不随着时间的推移而更新,你可以让它变得纯粹,只针对你的情况保持简单(今天,昨天,等等)。
@Pipe({
name:'timeAgo',
pure:false
})
export class TimeAgoPipe implements PipeTransform, OnDestroy {
private timer: number;
constructor(private changeDetectorRef: ChangeDetectorRef, private ngZone: NgZone) {}
transform(value:string) {
this.removeTimer();
let d = new Date(value);
let now = new Date();
let seconds = Math.round(Math.abs((now.getTime() - d.getTime())/1000));
let timeToUpdate = (Number.isNaN(seconds)) ? 1000 : this.getSecondsUntilUpdate(seconds) *1000;
this.timer = this.ngZone.runOutsideAngular(() => {
if (typeof window !== 'undefined') {
return window.setTimeout(() => {
this.ngZone.run(() => this.changeDetectorRef.markForCheck());
}, timeToUpdate);
}
return null;
});
let minutes = Math.round(Math.abs(seconds / 60));
let hours = Math.round(Math.abs(minutes / 60));
let days = Math.round(Math.abs(hours / 24));
let months = Math.round(Math.abs(days/30.416));
let years = Math.round(Math.abs(days/365));
if (Number.isNaN(seconds)){
return '';
} else if (seconds <= 45) {
return 'a few seconds ago';
} else if (seconds <= 90) {
return 'a minute ago';
} else if (minutes <= 45) {
return minutes + ' minutes ago';
} else if (minutes <= 90) {
return 'an hour ago';
} else if (hours <= 22) {
return hours + ' hours ago';
} else if (hours <= 36) {
return 'a day ago';
} else if (days <= 25) {
return days + ' days ago';
} else if (days <= 45) {
return 'a month ago';
} else if (days <= 345) {
return months + ' months ago';
} else if (days <= 545) {
return 'a year ago';
} else { // (days > 545)
return years + ' years ago';
}
}
ngOnDestroy(): void {
this.removeTimer();
}
private removeTimer() {
if (this.timer) {
window.clearTimeout(this.timer);
this.timer = null;
}
}
private getSecondsUntilUpdate(seconds:number) {
let min = 60;
let hr = min * 60;
let day = hr * 24;
if (seconds < min) { // less than 1 min, update every 2 secs
return 2;
} else if (seconds < hr) { // less than an hour, update every 30 secs
return 30;
} else if (seconds < day) { // less then a day, update every 5 mins
return 300;
} else { // update every hour
return 3600;
}
}
}https://stackoverflow.com/questions/57993462
复制相似问题