在写东西的时候发现须要这么一个东西,html
而也找不到有人写这个东东,那就本身写一个吧typescript
ng2+
的基础知识typescript
基础import { Pipe, PipeTransform } from "@angular/core";
function timeago(differtime: number, args: number = 5): string {
const currentYear: number = new Date().getFullYear(); // 获取当前的年份
// 不靠谱的时间戳映射
const TimetoSecond: any = {
year: new Date(`${currentYear}`).getTime() / 1000,
month: 30 * 86400,
day: 86400,
hour: 3600,
minute: 60,
};
if (differtime >= TimetoSecond.year) {
return parseInt(`${differtime / TimetoSecond.year}`, 10) + "年前";
}
if (differtime >= TimetoSecond.month) {
return parseInt(`${differtime / TimetoSecond.month}`, 10) + "月前";
}
if (differtime >= TimetoSecond.day) {
return parseInt(`${differtime / TimetoSecond.day}`, 10) + "天前";
}
if (differtime >= TimetoSecond.hour) {
return parseInt(`${differtime / TimetoSecond.hour}`, 10) + "小时前";
}
if (differtime >= TimetoSecond.minute) {
return parseInt(`${differtime / TimetoSecond.minute}`, 10) + "分钟前";
}
if (differtime < args) {
return "片刻以前";
} else {
return parseInt(`${differtime}`, 10) + "秒前";
}
}
@Pipe({
name: "longtimeago",
})
export class LongTimeagoPipe implements PipeTransform {
/** * * @param value 能够处理的值是字符串(能转为数字的)或者数字 * @param args 传入默认多少以后才进行处理,在此以前都是片刻 */
transform(value: string | number, args?: any): any {
// 获取今天的时间戳,并获得秒数
const currentTimeStamp: number = new Date().getTime();
if (value) {
let paramTimestamp: number = 0; //传入的时间戳
if (typeof value === "string") {
paramTimestamp = new Date(`${value}`).getTime();
if (Number.isNaN(paramTimestamp)) return null;
}
if (typeof value === "number") {
paramTimestamp = new Date(value).getTime();
}
const DifferTime = (new Date().getTime() - paramTimestamp) / 1000;
return timeago(DifferTime, args);
} else {
// 不然则返回原值
return null;
}
}
}
复制代码
在对应的modules
引入便可,好比你在app.modules.ts
bootstrap
import { LongTimeagoPipe } from '../pipe/LongTimeago.pipe';
// 这里省略了其余,为了更好的展现 , 在declarations引入便可在模块下的组件使用
@NgModule({
declarations: [
LongTimeagoPipe
],
imports: [
],
providers: [],
bootstrap: [AppComponent],
})
复制代码
|
以后就是管道<div class="last-reply-area">
<span>最后回复于:</span>
<span>{{listitem.last_reply_at |longtimeago}}</span>
</div>
复制代码
有不对之处尽请留言,会及时修正,谢谢阅读app