how do i compare current date with user input date from date picker

Chintan Soni picture Chintan Soni · Jun 16, 2013 · Viewed 11.9k times · Source

I am trying to keep constraint on date and time. I want that if user tries to set date less than current date then it should show alert, and same thing is to be done with time. I am using date and time pickers and my onDateSetListener and onTimeSetListener are as below:

DatePickerDialog.OnDateSetListener d = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                int dayOfMonth) {
            dateTime.set(Calendar.YEAR, year);
            dateTime.set(Calendar.MONTH, monthOfYear);
            dateTime.set(Calendar.DAY_OF_MONTH, dayOfMonth);
            update_date_display();



            // ---for setting notification----

            day = dayOfMonth;
            month = monthOfYear;
            AddEditTask.year = year;

            c.set(year, month, day);
        }
    };

    protected void update_date_display() {

        et_task_date.setText(formatDate.format(dateTime.getTime()));
    }

    TimePickerDialog.OnTimeSetListener t = new TimePickerDialog.OnTimeSetListener() {
        @Override
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

            dateTime.set(Calendar.HOUR_OF_DAY, hourOfDay);
            dateTime.set(Calendar.MINUTE, minute);
            update_time_display();

            // ---for setting notification---

            hour = hourOfDay;
            AddEditTask.minute = minute;

            c.set(Calendar.HOUR_OF_DAY, hourOfDay);
            c.set(Calendar.MINUTE, minute);
            c.set(Calendar.SECOND, 0);
        }
    };

    private void update_time_display() {

        et_task_time.setText(formatTime.format(dateTime.getTime()));
    }

can you please tell me what is to be written within those listeners to achieve what i want. Thanks in advance...!!!

Answer

Blackbelt picture Blackbelt · Jun 16, 2013

Create a new Date object this way:

Date now = new Date(System.currentTimeMillis());

and use int result = now.compareTo(theOtherDate);

result will be an int < 0 if now Date is less than the theOtherDate Date, 0 if they are equal, and an int > 0 if this Date is greater.