Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AmrMekkawy/b2b999278e6b5635a0ad53142c42980d to your computer and use it in GitHub Desktop.
Save AmrMekkawy/b2b999278e6b5635a0ad53142c42980d to your computer and use it in GitHub Desktop.
How to install moment package and use it in an Ionic typescript file and view (html) file?

How to install moment package and use it in an Ionic app?

This is a simple guide about how to install moment package and use it in an Ionic app, in both typescript files and view (html) files.

Install moment package

npm install moment --save-prod

Install moment-timezone package

npm install moment-timezone --save-prod

Import the package in the top of your TypeScript file

import * as moment from 'moment-timezone';

Note that we import the moment-timezone package not the moment package because this way we can use the methods of the moment-timezone package as well as the methods of the moment package because the moment-timezone package exports them.

Add it to the declared attributes or variables inside the class in your TypeScript file

export class ClassName {
    momentjs: any = moment;
    //..
    //..
}

Use moment package in your TypeScript file like this (for example)

// Set the default timezone to UTC
// More info about moment timezone: http://momentjs.com/timezone/docs
this.momentjs.tz.setDefault('UTC');

// Current datetime according to the default timezone (UTC as determined above)
let currentDateTime = this.momentjs().format('YYYY-MM-DD HH:mm:ss ZZ');
console.log(currentDateTime);

// A specific datetime according to a specific timezone ('Africa/Cairo' in this example) other than the default one (UTC as determined above)
let dateTimeAccordingToAnotherTimezone = this.momentjs('2018-10-15 15:59:59').tz('Africa/Cairo').format('DD-MM-YYYY @ hh:mm a ZZ');
console.log(dateTimeAccordingToAnotherTimezone);

Use moment package in your Ionic view file (html file) like this (for example)

<p>Order Placed at: {{ momentjs(order.created_at).tz('Africa/Cairo').format('DD-MM-YYYY @ hh:mm a') }}</p>



This question and answer also could be found on stackoverflow.com on this link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment