[筆記][Angular 2][Angular 4][Pipe] 將年月日時分秒 20170419135912 格式化成 2017/04/19 13:59:12 的 Pipe (DateTimeFormat)

小喵環境中,年月日時分秒是以14位數的文字來存放,當要展現時,要轉換為正常的日期時間格式。在 Angular 2 中可以透過 pipe 來處理。

緣起

小喵環境中,年月日時分秒是以14位數的文字來存放,當要展現時,要轉換為正常的日期時間格式。在 Angular 2 中可以透過 pipe 來處理。

例如: 20170419135912這樣的格式,小喵撰寫一個「DatetimeFormat」的pipe那麼就可以如下的處理

<span>{{'20170419140512'|DatetimeFormat}}</span>

撰寫Pipe

首先,新增一個檔案,名為「DatetimeFormat.pipe.ts」,要:

  • import Pipe, PipeTransform
  • @Pipe給予名稱
  • implements PipeTransform
  • 一個 transform 的 function,傳入value,回傳string

其內容如下:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'DatetimeFormat'
})
export class DatetimeFormatPipe implements PipeTransform {
  transform(value: string): string {
  	let rc:string='';
    if(value!=''){
      switch(value.length){

        case 8:
          rc = value.substr(0,4) + '/' + value.substr(4,2) + '/' + value.substr(6,2);
          break;

        case 12:
          rc = value.substr(0,4) + '/' + value.substr(4,2) + '/' + value.substr(6,2);
          rc += ' ' + value.substr(8,2) + ':' + value.substr(10,2);
          break;

        case 14:
          rc = value.substr(0,4) + '/' + value.substr(4,2) + '/' + value.substr(6,2);
          rc += ' ' + value.substr(8,2) + ':' + value.substr(10,2) + ':' +value.substr(12,2);
          break;

      }
    }
  	return rc;
  }
}

 

宣告Pipe在AppModule中

在「app.module.ts」中的「declarations」中,要把剛剛寫好的Pipe宣告進去,如下:

import { DatetimeFormatPipe } from './DatetimeFormat.pipe';
'...

@NgModule({
  declarations: [
    AppComponent,
    '...,
    DatetimeFormatPipe
  ],
  '...
})
export class AppModule { }

就醬子,很簡單,就完成囉

測試使用

在 app.component.html 中,我們加上以下的測試語法

<span>{{'20170419140512'|DatetimeFormat}}</span>

得到結果如下:

2017/04/19 14:05:12

小喵自己筆記,提供後續參考

^_^

 


以下是簽名:


Microsoft MVP
Visual Studio and Development Technologies
(2005~2019/6) 
topcat
Blog:http://www.dotblogs.com.tw/topcat