gpt4 book ai didi

angular - Angular 日期前管道吗?

转载 作者:行者123 更新时间:2023-12-03 18:36:33 27 4
gpt4 key购买 nike

我正在尝试创建帖子共享网站。我想以 Angular 创建日期前管道。

    import {Pipe, PipeTransform} from 'angular2/core';

@Pipe({
name: 'messageTime',
pure: false
})
export class MessageTimePipe implements PipeTransform {
transform(value: Date, []): string {
var result: string;

// current time
let now = new Date().getTime();

// time since message was sent in seconds
let delta = (now - value.getTime()) / 1000;

// format string
if (delta < 10) {
result = 'jetzt';
} else if (delta < 60) { // sent in last minute
result = 'vor ' + Math.floor(delta) + ' Sekunden';
} else if (delta < 3600) { // sent in last hour
result = 'vor ' + Math.floor(delta / 60) + ' Minuten';
} else if (delta < 86400) { // sent on last day
result = 'vor ' + Math.floor(delta / 3600) + ' Stunden';
} else { // sent more than one day ago
result = 'vor ' + Math.floor(delta / 86400) + ' Tagen';
}

return result;
}enter code here
}

我在我的项目中尝试像上面的代码。但它不能正常工作。

最佳答案

首先创建管道类

ng g p pipes/DateAgo

让我们添加这些代码,
  import {Pipe, PipeTransform} from '@angular/core';

@Pipe({
name: 'dateAgo',
pure: true
})
export class DateAgoPipe implements PipeTransform {

transform(value: any, args?: any): any {
if (value) {
const seconds = Math.floor((+new Date() - +new Date(value)) / 1000);
if (seconds < 29) // less than 30 seconds ago will show as 'Just now'
return 'Just now';
const intervals = {
'year': 31536000,
'month': 2592000,
'week': 604800,
'day': 86400,
'hour': 3600,
'minute': 60,
'second': 1
};
let counter;
for (const i in intervals) {
counter = Math.floor(seconds / intervals[i]);
if (counter > 0)
if (counter === 1) {
return counter + ' ' + i + ' ago'; // singular (1 day ago)
} else {
return counter + ' ' + i + 's ago'; // plural (2 days ago)
}
}
}
return value;
}

}

关于angular - Angular 日期前管道吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61341891/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com