最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to install moment.js package and use it in an Ionic app? - Stack Overflow

programmeradmin0浏览0评论

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?

Share Improve this question asked Oct 12, 2018 at 0:43 AmrAmr 5,1597 gold badges51 silver badges68 bronze badges 1
  • Possible duplicate of using moment.js package in ionic 2 project – Amr Abdalrahman Ahmed Commented Mar 6, 2019 at 9:35
Add a ment  | 

1 Answer 1

Reset to default 7

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

发布评论

评论列表(0)

  1. 暂无评论