在ionic 2项目中使用moment.js包

时间:2016-10-06 10:12:14

标签: angular ionic2

我想在Moment.js包中使用我的项目离子2中的日期,我不知道该怎么做 这是链接 moment js link

我有日期时间变量,我希望它来自我的区域。 我应该这样做吗?因为它是在javascript和ionic 2中使用的typescript

我试图这样做,但它不起作用

     constructor(public navCtrl: NavController,private platform:Platform) {

   mydate=new Date();
   mydate=moment.moment().format('MMMM Do YYYY, h:mm:ss a');

  }

当我尝试使用此

let data = moment().format('YYYYMMDD');
let time = moment().format('HHmmss');
console.log('today is: ', data + ' and time: ', time);

我得到这个错误 enter image description here

2 个答案:

答案 0 :(得分:47)

检查此link是否有打字稿。

通过NPM

1 - 安装

npm install moment -S
您在Typescript文件中

2 - 导入

import moment from 'moment';
在您的Typescript文件中

3 - 使用

let data = moment().format('YYYYMMDD');
let time = moment().format('HHmmss');
console.log('today is: ', data + ' and time: ', time);

我希望能给你一个帮助。 :)

编辑:依旧适用于Ionic v3.9.2(2018-03-08)

答案 1 :(得分:10)

谢谢@ mosca90,你让我90%的方式!

我使用您的信息创建自定义管道,完全解决了我的问题。这是管道的来源:

import { Pipe, PipeTransform } from '@angular/core';
import moment from 'moment';

/**
 * Generated class for the MomentjsPipe pipe.
 *
 * See https://angular.io/docs/ts/latest/guide/pipes.html for more info on
 * Angular Pipes.
 */
@Pipe({
  name: 'momentjs',
})
export class MomentjsPipe implements PipeTransform {
  /**
   * Takes a date value and returns a pretty string from current time, 
   * for instance: "four hours ago" or "in eleven minutes".
   */
  transform(value: string, ...args) {
    return moment(value).fromNow();
    //return value.toLowerCase();
  }
}

所以现在我可以这样做:

<div>{{ date | momentjs }}</div>

我看到了:

ten minutes ago.

完善!再次感谢你!

相关问题