在寫東西的時候發現須要這麼一個東西,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