如何在Angular2项目中将moment.js实现为管道

时间:2016-07-20 20:37:29

标签: javascript angular momentjs

我想在angular2项目中实现moment.js库我要将UTC时间转换为某个时区Europe/london,并使用moment和{{1} } 1

到目前为止,我已使用以下命令在我的Angular2项目中安装了[moment timezone]

  

npm install moment --save

这是我目前的代码:

moment.js

Html:

我从后端收到了作为对象的时间

import { Component, Pipe, PipeTransform } from '@angular/core';
import * as moment from 'moment';

@Pipe({ name: 'moment' })
class MomentPipe{
  transform(date, format) {
    return moment(date).format(format);
  }
}

它对我没用,我认为我的实施错误

4 个答案:

答案 0 :(得分:15)

当您需要使用它时,您必须在@component中指定它:

@Component({
    moduleId: module.id,
    templateUrl: './xyz.component.html',
    styleUrls: ['./xyz.component.css'],
    pipes: [MomentPipe],
    directives: [...]
})
public export ...

并以这种方式在html中使用它:

{{now | momentPipe:'YYYY-MM-DD'}}
不过,这是我编写管道的方法:

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

@Pipe({
    name: 'momentPipe'
})
export class MomentPipe implements PipeTransform {
    transform(value: Date|moment.Moment, ...args: any[]): any {
        let [format] = args;
        return moment(value).format(format);
    }
}

答案 1 :(得分:7)

更新:2018年6月

关于PIPES

的官方文档

要了解Moment in TypescriptMoment Date Formats

以下基于此处的问题给出的示例!使用PIPE技术,我们也可以在Angular View中使用矩(日期格式)。

MomentPipe.ts

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

@Pipe({ name: 'dateFormat' })
export class MomentPipe implements PipeTransform {
    transform(value: Date | moment.Moment, dateFormat: string): any {
        return moment(value).format(dateFormat);
    }
}

您必须将管道包含在AppModule的声明数组中。

import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { MomentPipe } from './momentPipe';

@NgModule({
  imports: [
    // Your Modules
  ],
  declarations: [
    AppComponent,
    // Your Components
    MomentPipe
  ],
  providers: [
    // Your Providers
  ]
})
export class AppModule { }

按如下所示在视图/ HTML中使用它。

{{ createdDate | dateFormat: 'MMMM Do YYYY, h:mm:ss a'}}

希望这会有所帮助。,

答案 2 :(得分:0)

尝试以下

export class MomentPipe implements PipeTransform {
transform(date, format) {
    return moment(date).format(format);
}
}

答案 3 :(得分:0)

使用ngx-moment-这是一个很棒的moment.js包装器,专为Angular 2+设计。

它几乎可以满足您的需要,并且可以满足您的情况:

 {{time.bookingTime.iso | amDateFormat:'MMMM Do YYYY, h:mm:ss a'}}