Prevent user from setting previous/future DateTime in Android

If your requirement is to restrict user to select older or future Date-time then here is the perfect solution…
First we will create user interface where user will select Date and Time and based on his input we will validate Date-Time.

Download Code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp">

    <android.support.design.widget.TextInputLayout
        android:id="@+id/dateTextInputLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <EditText
            android:id="@+id/dateEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Select Date" />

    </android.support.design.widget.TextInputLayout>

    <android.support.design.widget.TextInputLayout
        android:id="@+id/timeTextInputLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <EditText
            android:id="@+id/timeEditText"
            android:focusable="false"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Select Time" />

    </android.support.design.widget.TextInputLayout>

    <Button
        android:id="@+id/submitButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:background="@color/colorAccent"
        android:text="Submit" />

</LinearLayout>

Now let’s create function which will open DatePickerDialog

private void openDatePicker() {
        //We will consider current date here
        final Calendar c = Calendar.getInstance();
        int mYear = c.get(Calendar.YEAR);
        int mMonth = c.get(Calendar.MONTH);
        int mDay = c.get(Calendar.DAY_OF_MONTH);

        //This will open Date Picker Dialog
        DatePickerDialog datePickerDialog = new DatePickerDialog(this,
                new DatePickerDialog.OnDateSetListener() {

                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        dateEditText.setText(dayOfMonth + "-" + (monthOfYear + 1) + "-" + year);

                    }
                }, mYear, mMonth, mDay);
        datePickerDialog.show();
    }

Now let’s create function which will open TimePickerDialog

private void openTimePicker() {
        //We will consider current time here
        final Calendar c = Calendar.getInstance();
        int mHour = c.get(Calendar.HOUR_OF_DAY);
        int mMinute = c.get(Calendar.MINUTE);

        ////This will open Time Picker Dialog
        TimePickerDialog timePickerDialog = new TimePickerDialog(this,
                new TimePickerDialog.OnTimeSetListener() {

                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        timeEditText.setText(hourOfDay + ":" + minute);
                    }
                }, mHour, mMinute, false);
        timePickerDialog.show();
    }

Here is the core logic handling below, where we will restrict user

Restrict previous Date-Time selection ⚔ 

private void validateDateTime() {
        String selectedDate = dateEditText.getText().toString();
        String selectedTime = timeEditText.getText().toString();
        SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy HH:mm");
        Date mySelectedDate = null, myCurrentDate = null;
        try {
            mySelectedDate = format.parse(selectedDate + " " + selectedTime);
            myCurrentDate = new Date();
        } catch (ParseException e) {
            e.printStackTrace();
        }

        //Based on selected datetime millisecond and current datetime millisecond we will decide whether to restrict user or not
        if (mySelectedDate.getTime() / 1000L < myCurrentDate.getTime() / 1000L) {
            Toast.makeText(MainActivity.this, "Cannot proceed. You choose previous datetime.", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(MainActivity.this, "WOW !!! You can proceed now.", Toast.LENGTH_LONG).show();
        }      
    }
Restrict FUTURE Date-Time selection ⚔ 

private void validateDateTime() {
        String selectedDate = dateEditText.getText().toString();
        String selectedTime = timeEditText.getText().toString();
        SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy HH:mm");
        Date mySelectedDate = null, myCurrentDate = null;
        try {
            mySelectedDate = format.parse(selectedDate + " " + selectedTime);
            myCurrentDate = new Date();
        } catch (ParseException e) {
            e.printStackTrace();
        }     

        //Based on selected datetime millisecond and current datetime millisecond we will decide whether to restrict user or not
        if (mySelectedDate.getTime() / 1000L > myCurrentDate.getTime() / 1000L) {
            Toast.makeText(MainActivity.this, "Cannot proceed. You choose future datetime.", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(MainActivity.this, "WOW !!! You can proceed now.", Toast.LENGTH_SHORT).show();
        }
    }

Hurray 🎊🎉

You are done… Hope you got it…

Leave a Reply

Be the First to Comment!

avatar
  Subscribe  
Notify of