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

21,018

Solution 1

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.,

Solution 2

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

Solution 3

Try below

export class MomentPipe implements PipeTransform {
transform(date, format) {
    return moment(date).format(format);
}
}
Share:
21,018
Hamza L.
Author by

Hamza L.

Updated on September 21, 2021

Comments

  • Hamza L.
    Hamza L. over 2 years

    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 using moment and [moment timezone] 1

    So far, I have installed moment.js in my Angular2 project using the following command:

    npm install moment --save

    Here is my current code:

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

    The Html:

    I received the time from the backend as an object

    //time.bookingTime.iso == 2016-07-20T21:00:00.000Z
    
     {{time.bookingTime.iso | moment}}
    

    It didn't work for me and I think that I have wrong implementation

  • Hamza L.
    Hamza L. almost 8 years
    It's the exact same thing that I am having, except your code is for TypeScript not JavaScript
  • ajbeaven
    ajbeaven almost 8 years
    When changing the variable passed in to the pipe (in your case, now), I found that the pipe wasn't executed, presumably because the change isn't a pure change. I used @Pipe({ name: 'momentPipe', pure: false }) to make this an impure pipe which fixed this problem.
  • Niraj
    Niraj over 7 years
    This wont work unless the string you passed will be enclosed in square brackets. i.e the line should be modified as - {{now | momentPipe:['YYYY-MM-DD']}} This is because argument received by pipe has data type array of type any.
  • Sierrodc
    Sierrodc over 7 years
    @Niraj The typescript code uses Spread Operator (basarat.gitbooks.io/typescript/content/docs/…). This operator converts the list of parameters to an array. So it is wrong to to send an array to the transform function.
  • Niraj
    Niraj over 7 years
    @Sierrodc but i am sending array and only then its working. Otherwise its no taking the rest of the argument. ex - if i pass "DD-MM-YYYY", the output will be current day i.e 22 only and not in the entire format.
  • Sierrodc
    Sierrodc over 7 years
    @Niraj I don't know your implementatino but, If I write something like momentPipe:'YYYY-MM-DD':'something':'else' in the template, then in typescript I have args = ['YYYY-MM-DD':'something':'else']. I don't know why you need to specify square brakets. Which browser are you using? typescript version? angular version?
  • guyaloni
    guyaloni about 7 years
    Important thing (at least for ionic): to import a pipe, now need to add it to @NgModule, to declarations array.
  • György Balássy
    György Balássy over 5 years
    Works very well after npm install moment --save, thank you @RajeshKdev.
  • RajeshKdev
    RajeshKdev over 5 years
    You are Welcome, Glad that helped you!!
  • Sergey Shamanayev
    Sergey Shamanayev over 2 years
    Also with null and async transform(value: Date | moment.Moment | null, dateFormat: string = 'YYYY-MM-DD'): string { return moment(value).format(dateFormat); } {{ createdDate | async | dateFormat: 'MMMM Do YYYY, h:mm:ss a'}}