ionic 3 学习笔记

Ionic 3 日期时间处理:@Pipe + date-fns

2018-05-18  本文已影响168人  与蟒唯舞
安装date-fns库
$ npm install date-fns --save
生成 pipe
$ ionic g pipe relative-time
src/app/app.module.ts 文件中导入 PipesModule
import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';

import { PipesModule } from '../pipes/pipes.module';

@NgModule({
  declarations: [
    MyApp,
    HomePage
  ],
  imports: [
    BrowserModule,
    PipesModule,
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}
修改生成的 relative-time.ts 文件
import { Pipe, PipeTransform } from '@angular/core';
import distanceInWordsToNow from 'date-fns/distance_in_words_to_now';
import zhCN from 'date-fns/locale/zh_cn';
import enUS from 'date-fns/locale/en';

@Pipe({
  name: 'relativeTime',
})
export class RelativeTimePipe implements PipeTransform {

  transform(value: string, ...args) {
    const locale = args[0] == 'zh' ? zhCN : enUS;
    return distanceInWordsToNow(new Date(value), {
      addSuffix: true,
      locale
    });
  }
}
使用

home.html

<ion-header>
  <ion-navbar>
    <ion-title>
      @Pipe + date-fns
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content text-center>
  {{time}} 经过处理后显示:
  <h2>{{ time| relativeTime:'zh'}} </h2>
  <h2>{{ time| relativeTime:'en'}} </h2>

</ion-content>

home.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  time: string;
  constructor(public navCtrl: NavController) {
    this.time = '2018-05-10';
  }

}
实现效果
上一篇 下一篇

猜你喜欢

热点阅读