Android DatePickerDialog - Get and Set DateTime


In this class we see how to set and retrieve date via the DatePickerDialog widget.

datepicker

DatePickerDialog allows us to pick and set dates. Those dates can be set programmatically or via the datetimepicker component.

In this class let's see how to do both.

If you prefer a video tutorial or want to watch the demo please see the video below:



DatePickerDialog resides in the android.widget package and as we have said allows us set date and pick the set dates.

To set date basically this is what we do:

new DatePickerDialog(this, myDateSetListener, myYear,myMonth, myDay);

Instantiate the DatePickerDialog passing in a Context,android.app.DatePickerDialog.OnDateSetListener,year month and day.

You can use the Calender class to get those year,month and date:

// Get Year, Month and Day From java.util.Calendar
        final Calendar c = Calendar.getInstance();
        myYear = c.get(Calendar.YEAR);
        myMonth = c.get(Calendar.MONTH);
        myDay = c.get(Calendar.DAY_OF_MONTH);

But first we need to have instantiated that OnDateListener and overridden the onDateSet() method:

 myDateSetListener = new OnDateSetListener() {
            //when date is set
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear,int dayOfMonth) {
                //get the set date and show in a Toast message
                Toast.makeText(MainActivity.this,String.valueOf(dayOfMonth)+" : "+String.valueOf(monthOfYear)+" : "+ String.valueOf(year), Toast.LENGTH_SHORT).show();
            }
        };

Let's look at a complete example:

1. activity_main.xml

Here's our layout. At the root we have a RelativeLayout.

Inside it we have a TextView which is our header label.

Then a simple button that when clicked will show our DatePickerDialog.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingLeft="5dp"
    android:paddingRight="5dp"
    tools:context="info.camposha.mydatepicker.MainActivity">

    <TextView
        android:id="@+id/headerLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:fontFamily="casual"
        android:text="DatePicker - Get and Set"
        android:textAllCaps="true"
        android:textSize="24sp"
        android:textStyle="bold" />

    <Button
        android:id="@+id/showDatePicker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Date Picker"
        android:background="@android:drawable/edit_text"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" />
</RelativeLayout>

2. MainActivity.java

Here's our main activity class:

First we specify the package our class will reside in. Then add our imports, including android.widget.DatePicker and android.app.DatePickerDialog.

We'll make our class derive from android.app.Activity, the base activity class.

Then define our instance fields.

We'll have a method called getAndSet() that will first, using the Calender class, get the current Date.

Then instantiate the android.app.DatePickerDialog.OnDateSetListener, get the selected date and show in a Toast message.

We'll override the onCreateDialog() method of the Activity class and instantiate a DatePickerDialog and return it. We pass to it our date that we had obtained from the java.Util.Calender.

package info.camposha.mydatepicker;

import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.Toast;

public class MainActivity extends Activity {

    private static final int MY_DATE_PICKER = 0;
    private OnDateSetListener myDateSetListener;
    int myYear;
    int myMonth;
    int myDay;

    /*
    when activity is created
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button showDatePickerBtn=findViewById(R.id.showDatePicker);
        showDatePickerBtn.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showDialog(MY_DATE_PICKER);
                    }
                });
        getAndSetDate();
    }
    /*
    Get and Set dates
     */
    private void getAndSetDate()
    {
        // Get Year, Month and Day From java.util.Calendar
        final Calendar c = Calendar.getInstance();
        myYear = c.get(Calendar.YEAR);
        myMonth = c.get(Calendar.MONTH);
        myDay = c.get(Calendar.DAY_OF_MONTH);

        //Listen to date set events
        myDateSetListener = new OnDateSetListener() {
            //when date is set
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear,int dayOfMonth) {
                //get the set date and show in a Toast message
                Toast.makeText(MainActivity.this,String.valueOf(dayOfMonth)+" : "+String.valueOf(monthOfYear)+" : "+ String.valueOf(year), Toast.LENGTH_SHORT).show();
            }
        };
    }
    /*
    When any dialog is created
     */
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case MY_DATE_PICKER:
                return new DatePickerDialog(this, myDateSetListener, myYear,myMonth, myDay);
        }
        return super.onCreateDialog(id);
    }
}

That's it.

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think


Previous Post Next Post