Using Moment JS as a Pipe Angular or Ionic

Thulani Mtetwa
1 min readNov 28, 2017

--

After some frustrations of try to use the date pipe in Angular and it not being able to handle date formats on Safari or Ionic iOS hybrid applications I was then inspired to write this tutorial after searching the web for a simple straightforward solution.

$ ionic start MomentInTime blank $ cd ./MomentInTime$ ionic g pipe moment$ npm install --save moment

Now thats done let’s head over to src/app/app.module.ts file and add a couple of lines of code.

...
import { MomentPipe} from '../pipes/moment/moment';
...
@NgModule({
declarations: [//Add moment here
MomentPipe,
],
,
imports: []
...
});
...

Okay. So far so good. Now let’s go change something in src/pipes/moment/moment.ts file. Copy and paste the following

import * as moment from 'moment';...
transform(date, format) {
return moment(date).format(format);
}

Now head over to any place where you want to apply the Pipe. In my case it’s the following situation; src/pages/home/home.ts

...
date : any;
constructor(public navCtrl: NavController) {
this.date = new Date();
}
...

Now this is me applying the pipe.

...
<ion-content padding>
<h1 text-center> The time is {{date | moment:'HH:mm'}}</h1>
</ion-content>
...

--

--

Thulani Mtetwa
Thulani Mtetwa

Written by Thulani Mtetwa

I am an iOS App Developer. And worked on multiple apps in the finance and insurance industry.

Responses (1)