How to install moment.js
package to an application that built with Ionic framework. And how to use it in the app, in both the .ts
files and the .html
files?
How to install moment.js
package to an application that built with Ionic framework. And how to use it in the app, in both the .ts
files and the .html
files?
- Possible duplicate of using moment.js package in ionic 2 project – Amr Abdalrahman Ahmed Commented Mar 6, 2019 at 9:35
1 Answer
Reset to default 7This is a simple guide about how to install moment.js
package and use it in an Ionic app, in both the typescript files and the view (html) files.
Install moment.js
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" is a name of my choice, you can name it as you like
momentjs: any = moment;
//..
//..
}
Use moment.js
package in your TypeScript file like this (for example)
// Set the default timezone to UTC
// More info about moment timezone: http://momentjs./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.js
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 will display the date and time according to the specified timezone and in the specified format.