Angular 2 + Ionic 2: How to change the format of the date in the controller?

advertisements

I'm getting date in loop from sqlite database. The format is like "Wed Feb 01 2017 21:54:24 GMT-0200". But I want to change it as 'dd/MM/yyyy'.

How can I change format in the controller?

Example my code:

this.issuedService.fetchAll().then(( res ) => {
    var data = [];
    for (let entry  of <Array<any>>res) {
        console.log( JSON.stringify( entry  ) );
    }
    //this.items = <Array<any>>res;
}, ( error ) => {
    console.log( "ERROR: ", error.message );
});

UPDATE 2017-02-02

So, after a few hours without sleep, I finally found a solution.

I can add MomentJs libraries to my Ionic v2 project from NPM.

$ npm install moment --save

The result code:

import { Component } from '@angular/core';

import { NavController, NavParams } from 'ionic-angular';

import * as moment from 'moment';
import 'moment/locale/pt-br';

import { IssuedService } from '../../providers/issued-service';

@Component( {
    selector: 'page-home',
    templateUrl: 'home.html'
})

export class HomePage {
    items: any[] = [];
    issuedPage = IssuedPage;

    constructor(
        public navCtrl: NavController,
        public navParams: NavParams,
        public issuedService: IssuedService
    ) {
        this.initializeItems();
    }

    ionViewDidLoad() {
        console.log( 'ionViewDidLoad HomePage' );
    }

    initializeItems() {
        this.issuedService.fetchAll().then(( res ) => {
            for ( let entry of <Array<any>>res ) {
                entry.query_dt = moment( entry.picking_dt ).format( 'DD MMMM YYYY' );
                this.items.push(entry);
            }
            console.log( JSON.stringify( this.items  ) );
        }, ( error ) => {
            console.log( "ERROR: ", error.message );
        });
    }
}

Ionic 2 Doc / Adding third party libs


The solution to my project:

Adding third party libs

You can add most third party libraries to your V2 project from NPM. For example let’s add MomentJs.

 $ npm install moment --save

From here, we can import it into what ever class we want to use it in.

import {Page} from 'ionic-angular';
import * as moment from 'moment';

export class MyClass {
  constructor(){
    moment("20111031", "YYYYMMDD").fromNow();
  }

}

Ionic Documentation Code