I would like to implement moment.js library inside an angular2 project i order to convert a UTC
time to a certain time zone Europe/london
and that
When you need to use it, you have to specify it in the @component:
@Component({
moduleId: module.id,
templateUrl: './xyz.component.html',
styleUrls: ['./xyz.component.css'],
pipes: [MomentPipe],
directives: [...]
})
public export ...
and use it in the html in this way:
{{now | momentPipe:'YYYY-MM-DD'}}
btw, this is my way to write the pipe:
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);
}
}
Try below
export class MomentPipe implements PipeTransform {
transform(date, format) {
return moment(date).format(format);
}
}
Use ngx-moment - it's an awesome moment.js wrapper designed for Angular 2+.
It can do pretty much anything you need out of the box, and in your case:
{{time.bookingTime.iso | amDateFormat:'MMMM Do YYYY, h:mm:ss a'}}
Update: June 2018
Official Documentation about PIPES
To learn about Moment in Typescript and Moment Date Formats.
Example given below based on the Question here! Using PIPE
technique we can use moment in Angular View as well (Date Formatting).
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);
}
}
You must include your pipe in the declarations array of the 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 { }
Use it in your View/Html like below.,
{{ createdDate | dateFormat: 'MMMM Do YYYY, h:mm:ss a'}}
Hope this helps.,