Angular 2.x折腾记 :(11) 写一个挺不靠谱的多少秒/分/时/天前的管道

1,622 阅读1分钟

前言

在写东西的时候发现需要这么一个东西,

而也找不到有人写这个东东,那就自己写一个吧

效果图

  • 之前

  • 用了管道之后

前置基础

  • ng2+的基础知识
  • typescript基础

实现代码

  • LongTimeago.pipe.ts

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

  • app.module.ts
import { LongTimeagoPipe } from '../pipe/LongTimeago.pipe';

// 这里省略了其他,为了更好的展示 , 在declarations引入即可在模块下的组件使用
@NgModule({
  declarations: [
    LongTimeagoPipe
  ],
  imports: [
  ],
  providers: [],
  bootstrap: [AppComponent],
})

  • app.component.html , | 之后就是管道

  <div class="last-reply-area">
        <span>最后回复于:</span>
        <span>{{listitem.last_reply_at |longtimeago}}</span>
      </div>

总结

有不对之处尽请留言,会及时修正,谢谢阅读