Using Date Picker in Ionic Capacitor

 In this tutorial we are going to explain how to date picker in your ionic application using capacitor. To implement data picker we are using capacitor community plugin which is maintain by capacitor community.

To install this community plugin in your project you need to run following in your terminal window.

npm install @capacitor-community/date-picker

After the successful installation you need to import this plugin with in your component.

import { Plugins } from "@capacitor/core";
import { DatePickerPluginInterface } from "@capacitor-community/date-picker";

const DatePicker: DatePickerPluginInterface = Plugins.DatePickerPlugin as any;
const selectedTheme = "dark";

To show the date picker you just need to call the below function.

openDatePicker() {
DatePicker
  .present({
    mode: "date",
    locale: "pt_BR",
    format: "dd/MM/yyyy",
    date: "28/06/2021",
    theme: selectedTheme,
  })
  .then((date) => console.log(date.value));}

You can also set this setting in your capacitor config and use them.

{
  "plugins": {
    "DatePickerPlugin": {
      "mode": "date",
      "locale": "pt_BR",
      "current": "28/06/2021",
      "format": "dd/MM/yyyy"
    }
  }
}

There is lot options available which you use with in openDatePicker function like time zone, min date, max date and mode. There is list of all option which we have with this plugin for android.

name type default
format string "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
locale string current device
date string current date
mode DatePickerMode "dateAndTime"
theme DatePickerTheme "light"
timezone string current device
min string null
max string null
doneText string "OK"
cancelText string "Cancel"
is24h boolean false

For using this plugin in android studio you need to do some setup. Basically you need to import this plugin with in your MainActivity.java using below code

import com.getcapacitor.community.datepicker.DatePickerPlugin;

and then inside of your init callback you need to initalize you plugin

add(DatePickerPlugin.class);

After this you just need to run you project in your android studio and date picker with open within your app.


Note- This plugin will not works with capacitor 3 that is currently under development. Once the developer will launch this plugin for capacitor 3 we will create separate tutorial for that.

Thanks for learning!

Post a Comment

0 Comments