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

How to implement moment.js as a pipe in an Angular2 project

本文关键字:js moment 实现 管道 Angular2 项目      更新时间:2023-09-26

我想在angular2项目中实现moment.js库,以便将UTC时间转换为某个时区Europe/london,并使用moment[moment timezone] 1

到目前为止,我已经使用以下命令在Angular2项目中安装了moment.js

npm安装时刻--保存

这是我当前的代码:

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}}

它对我不起作用,我认为我有错误的实现

更新:2018年6月

关于PIPES的官方文档

要了解字体中的Moment和Moment日期格式

下面给出的例子基于这里的问题!使用PIPE技术,我们也可以在角视图中使用矩(日期格式)。

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 { }

在您的View/Html中使用它,如下所示

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

希望这能有所帮助。,

当您需要使用它时,您必须在@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);
    }
}

尝试低于

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

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

它几乎可以开箱即用地做任何你需要的事情,在你的情况下:

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