我想在angular2项目中实现moment.js库我命令将UTC时间转换为某个时区Europe / london并使用时刻和[时刻时区]
1
到目前为止,我已使用以下命令在我的Angular2项目中安装了moment.js:
npm install moment –save
这是我目前的代码:
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);
}
}
Html:
我从后端收到了作为对象的时间
//time.bookingTime.iso == 2016-07-20T21:00:00.000Z
{{time.bookingTime.iso | moment}}
它对我不起作用,我认为我的实施错误
解决方法
当您需要使用它时,您必须在@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);
}
}