Use Moment.js with angular2 application

Recently i was developing an application in angular2 where i had to use a calendar which shows the results for this month, this week and this weekend. I was finding a solution in pure javascript but it was time consuming. I decided to go on with moment.js , this is how i have embedded moment with angular2 application.

Step 1 : npm install moment –save

Step 2 : In your systemjs.config.js file’s map array add:

‘moment’: ‘node_modules/moment’

to packages array add:

‘moment’: { defaultExtension: ‘js’ }

Step 3 : In your component.ts use: import * as moment from 'moment/moment';

and that’s it. Now you should be able to use moment with your application.


public setDate(term: string) {
var status: string;
status = term;
switch (status) {
case "today":
this.fromDate = moment().toDate();
case "tomorrow":
this.fromDate = moment(new Date()).add(1,'days').toDate();
case "weekend":
this.fromDate = moment().startOf('week').add('days', 6).toDate();;
this.toDate = moment().startOf('week').add('days', 7).toDate();
case "thisweek":
this.fromDate = moment().startOf('week').toDate();;
this.toDate = moment().startOf('week').add('days', 7).toDate();
case "nextweek":
this.fromDate = moment().startOf('week').add('days', 7).toDate();
this.toDate = moment().startOf('week').add('days', 14).toDate();
case "thismonth":
var date = new Date(), y = date.getFullYear(), m = date.getMonth();
var firstDay = new Date(y, m, 1);
var lastDay = new Date(y, m + 1, 0);
this.fromDate = moment(firstDay).toDate();
this.toDate = moment(lastDay).toDate();

2 thoughts on “Use Moment.js with angular2 application

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.