Ionic | Working with moments.js

Inhaltsverzeichnis [Anzeigen]

Introduction

With moment.js, you can

Parse, validate, manipulate, and display dates and times in JavaScript.

With a npm-Module, you can integrate this functionality into your Ionic App

Preparation

Create your empty app

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$ ionic start working-with-moments blank --no-git --no-link
$ ionic start working-with-moments blank --no-git --no-link
$ ionic start working-with-moments blank --no-git --no-link

Install npm Module

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$ cd working-with-moments
$ npm install moment
+ moment@2.20.1
added 1 package in 3.001s
cdworkingwithmoments npm install moment + moment@2.20.1 added 1 package in 3.001s
$ cd  working-with-moments
$ npm install moment
+ moment@2.20.1
added 1 package in 3.001s

Start Editor and serve your app

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$ vscode .
$ ionic serve
vscode. ionic serve
$ vscode .
$ ionic serve

Add moments.js functionality

Change pages/home/home.ts

Add the moments.js reference to pages/home/home.ts

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import * as moment from 'moment';
import { Component } from '@angular/core'; import { NavController } from 'ionic-angular'; import * as moment from 'moment';
import { Component } from '@angular/core'; 
import { NavController } from 'ionic-angular';
import * as moment from 'moment';

Create a var for the current date/time

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
export class HomePage {
public date: any;
constructor(public navCtrl: NavController) {
this.date = moment();
}
}
export class HomePage { public date: any; constructor(public navCtrl: NavController) { this.date = moment(); } }
export class HomePage {
  public date: any;

  constructor(public navCtrl: NavController) {
    this.date = moment();
  }
}

Change pages/home/home.html

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<ion-content padding>
The current date/time is {{ date }}
</ion-content>
<ion-content padding> The current date/time is {{ date }} </ion-content>
<ion-content padding>
  The current date/time is {{ date }}
</ion-content>

Summary

A lot more examples could be found in my repository. Just create a starter app with this template and begin to play

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$ ionic start app https://github.com/ionic4-toolbox/Working-with-moment.js
$ ionic start app https://github.com/ionic4-toolbox/Working-with-moment.js
$ ionic start app https://github.com/ionic4-toolbox/Working-with-moment.js