如何安装 moment.js 包并在 Ionic 应用程序中使用它?

Amr*_*Amr 1 javascript momentjs ionic-framework

如何将moment.js包安装到使用 Ionic 框架构建的应用程序中。以及如何在应用程序中,在.ts文件和.html文件中使用它?

Amr*_*Amr 6

这是一个关于如何安装moment.js包并在 Ionic 应用程序中使用它的简单指南,包括打字稿文件和视图 (html) 文件。

安装moment.js

npm install moment --save-prod
Run Code Online (Sandbox Code Playgroud)


安装moment-timezone

npm install moment-timezone --save-prod
Run Code Online (Sandbox Code Playgroud)


在 TypeScript 文件的顶部导入包

import * as moment from 'moment-timezone';
Run Code Online (Sandbox Code Playgroud)

请注意,我们导入的是moment-timezone包,而不是moment包,因为这样我们可以使用moment-timezone包的方法以及moment包的方法,因为moment-timezone包导出它们。


将它添加到 TypeScript 文件中类中声明的属性或变量中

export class ClassName {
    // "momentjs" is a name of my choice, you can name it as you like
    momentjs: any = moment;
    //..
    //..
}
Run Code Online (Sandbox Code Playgroud)


moment.js像这样在你的 TypeScript 文件中使用包(例如)

// 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);
Run Code Online (Sandbox Code Playgroud)


moment.js在您的 Ionic 视图文件(html 文件)中使用package 像这样(例如)

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

这将根据指定的时区和指定的格式显示日期和时间。