Ionic 5 Datepicker & Timepicker using Cordova, Native plugin Tutorial with Example

In this Ionic 5/4 tutorial, we are going to implement native-like sliding Datapicker and Timepicker using Cordova and Native plugins.

To give a more native look to the Ionic applications we can replace HTML based Date & Time picker with Android’s Native Date and Time picker in Ionic hybrid applications. Ionic’s Native Datetime Picker plugin allows adding a sliding Android Date and Time picker with many custom options and themes.

After implementation, the native Date and Timepicker will look like this

 

Date picker Slider Dialog

Time picker Slider Dialog

 

Let’s get started!

 

 

Supported Platforms

  • Android
  • iOS
  • Windows

 

Install/ Update Ionic CLI

We are going to build a new Ionic application using the Ionic Framework 5. You can install or update by running below command

$ npm install -g @ionic/cli

Create a New Ionic Application

Run the following command to create a new Ionic application with a blank template.

$ ionic start ionic-date-timepicker-native-app blank --type=angular

Install Date Picker Cordova and Native plugin

Run following commands one by one to install the Cordova plugin and its Native wrapper to enable us to access its native methods via javaScript.

$ ionic cordova plugin add cordova-plugin-datepicker
$ npm install @ionic-native/date-picker

Import Date Picker plugin in App’s Module

After the successful installation of the Date picker plugin, we need to import its class in the app’s main module so that its methods are available throughout the application.

Open the app.module.ts file to import DatePicker class then update the providers Array:

//app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';

import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';

import { DatePicker } from '@ionic-native/date-picker/ngx';

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [
    BrowserModule, 
    IonicModule.forRoot(), 
    AppRoutingModule
  ],
  providers: [
    StatusBar,
    SplashScreen,
    DatePicker,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

 

Adding Date & Time Pickers

As we created the Ionic application using a blank template, so we already have a Home Component. In the Home template, we will add three buttons to get Date, Time, and Both Date Time.

 

Update Home Page Template

Replace below code in the home.page.html file to call methods to show date and time pickers:

<ion-header>
  <ion-toolbar color="tertiary">
    <ion-title>
      Ionic 4 Native Date Time Picker
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content padding>
<h1>Date & Time Pickers</h1>

  <ion-button (click)="showDatepicker()">
    Show Date Picker
  </ion-button>
  <h4>Date: {{myDate}}</h4>

  <ion-button (click)="showTimepicker()">
    Show Time Picker
  </ion-button>
  <h4>Time: {{myTime}}</h4>


  <ion-button (click)="showDateTimepicker()">
    Show Date & Time Picker
  </ion-button>
  <h4>Date & Time: {{myDateNTime}}</h4>

</ion-content>

In the template, we are only calling methods to open the dialogs for Date and Time selection by users and showing the selected values in the myDate, myTime and myDateNTime variables.

 

Update Home Component Class

To show the Date and Time Picker we will import DatePicker class in our home component:

import { DatePicker } from '@ionic-native/date-picker/ngx';

 

Then add in the constructor of the class:

  constructor(
    private datePicker: DatePicker
  ) {}

 

Also, define three variables of type stringto keep the selected date and time values.

  myDate:string;
  myTime:string;
  myDateNTime:string;

Show DateTime Picker

To show DateTime picker we call show() method of DatePicker class which returns a promise. It also takes optional configurations:

this.datePicker.show({
  date: new Date(),
  mode: 'date',
  androidTheme: this.datePicker.ANDROID_THEMES.THEME_HOLO_DARK
}).then(
  date => console.log('Got date: ', date),
  err => console.log('Error occurred while getting date: ', err)
);

 

Finally, update the home.page.ts file with following complete code:

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

import { DatePicker } from '@ionic-native/date-picker/ngx';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {

  myDate:string;
  myTime:string;
  myDateNTime:string;

  constructor(
    private datePicker: DatePicker
  ) {}

  showDatepicker(){
    this.datePicker.show({
      date: new Date(),
      mode: 'date',
      androidTheme: this.datePicker.ANDROID_THEMES.THEME_HOLO_DARK,
      okText:"Save Date",
      todayText:"Set Today"
    }).then(
      date => {
        this.myDate = date.getDate()+"/"+date.toLocaleString('default', { month: 'long' })+"/"+date.getFullYear();
      },
      err => console.log('Error occurred while getting date: ', err)
    );
  }  


  showTimepicker(){
    this.datePicker.show({
      date: new Date(),
      mode: 'time',
      androidTheme: this.datePicker.ANDROID_THEMES.THEME_HOLO_LIGHT,
      okText:"Save Time",
      nowText:"Set Now"
    }).then(
      time => {
        this.myTime =  time.getHours()+":"+time.getMinutes();
      },
      err => console.log('Error occurred while getting time: ', err)
    );
  }  


  showDateTimepicker(){
    this.datePicker.show({
      date: new Date(),
      mode: 'datetime',
      androidTheme: this.datePicker.ANDROID_THEMES.THEME_TRADITIONAL,
      doneButtonLabel:"Save Date & Time",
      is24Hour:false
    }).then(
      dateTime => {
        this.myDateNTime = dateTime.getDate()+"/"+dateTime.toLocaleString('default', { month: 'long' })+"/"+dateTime.getFullYear()+" "+dateTime.getHours()+":"+dateTime.getMinutes();
      },
      err => console.log('Error occurred while getting dateTime: ', err)
    );
  }  

}

In the above method, we have added some important options:

mode: The mode of the date picker, can be “date | time | datetime
date: Selected date

minDate: Minimum date

maxDate: Maximum date

titleText: Label for the dialog title

okText: The label of BUTTON_POSITIVE (done button)

cancelText: The label of BUTTON_NEGATIVE (cancel button)

todayText: Label of today button. If empty, doesn’t show the option to select current date

nowText: The label of now button. If empty, doesn’t show the option to select the current time

is24Hour: Shows time dialog in 24 hours format

 

Date & Time Picker Themes

We can apply any theme by setting the androidTheme property inside the show() method.

androidTheme: Choose the Android theme for the picker. You can use the DatePicker.ANDROID_THEMES property. These themes are available  THEME_TRADITIONAL | THEME_HOLO_DARK | THEME_HOLO_LIGHT | THEME_DEVICE_DEFAULT_DARK | THEME_DEVICE_DEFAULT_LIGHT

 

That’s now to check this Native date picker you need to run the app in a real device.

 

Run Application in Real Device

To check vibration functionality, you need to run the application in a real device. For that, you need to add the Platform for which you are going to build the application.

Add Platform in Application

Run the following command in the terminal to install the required platform

# Add Android
$ ionic cordova platform add android

# Add iOS
$ ionic cordova platform add ios

# Add Windows
$ ionic cordova platform add windows

 

Build Runnable File

After adding the platform, you can run the following commands to create an executable file like APK file for Android. Or you can simply run the app in the USB connected mobile with USB Debugging enabled discussed in the next step.

# Build Android
$ ionic cordova build android

# Build iOS
$ ionic cordova build ios

# Build Windows
$ ionic cordova build windows

 

Live Run Application in USB connected Device

If you just want to run the application in the real device and debug it on the Chrome browser, just execute the following command after connecting your mobile to your computer

# Live Run on Android
$ ionic cordova run android -l

# Live Run on iOS
$ ionic cordova run ios -l

# Live Run on Windows
$ ionic cordova run windows -l

 

Conclusion

Finally, we implemented the DatePicker Native plugin that adds native look to Ionic application and with a lot of options, it becomes easy to configure according to the needs of the application using Cordova and Native plugin in an Ionic application. We also discussed how to add platform and test application in a real device to check native features.

If you enjoyed the content. Do share with other geeks. Thanks for reading!

 

 

 

 

 

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments