MoonStarCoder
MoonStarCoder

Reputation: 3

Android, check that a date from datepicker is not in the future

In my activity, a user can select a date via datepicker. I what to ensure, that the selected date does not lie in the futur.

What it got so far:

private String textStart="";
    private String textEnd="";
    private String setToday="";

calendar = Calendar.getInstance();
        year = calendar.get(Calendar.YEAR);
        month = calendar.get(Calendar.MONTH);
        day = calendar.get(Calendar.DAY_OF_MONTH);
        setToday = day+"/"+(month+1)+"/"+year;

when i pick date from datepicker

private DatePickerDialog.OnDateSetListener myDateListener
        = new DatePickerDialog.OnDateSetListener() {

    @Override
    public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) {
        // TODO Auto-generated method stub
        // arg1 = year
        // arg2 = month
        // arg3 = day
        showDateStart(arg1, arg2 + 1, arg3);
    }

call method showDateStart for check scope of date

private void showDateStart(int year, int month, int day) {
        textDateStart.setText(new StringBuilder().append(day).append("/")
                .append(month).append("/").append(year));
        startStamp=true;
        textStart = day+"/"+month+"/"+year;
        if(textStart.compareTo(setToday)>0){
            textStart = setToday;
            Toast.makeText(getActivity(), "out of scope::"+setToday,
                    Toast.LENGTH_LONG).show();
            textDateStart.setText(setToday);
        }

    }

but not work if i pick 1/1/2016 because today is 22/2/2015 value of textStart not more than settoday

sorry for my mistake it first question.

As a bonus: Is it possible to restrict the datepicker to only display dates up to today?

Upvotes: 0

Views: 1598

Answers (1)

Morteza Soleimani
Morteza Soleimani

Reputation: 2670

you can get the underlying DatePicker from a DatePickerDialog (by simply calling getDatePicker()) and set its bounds using:

Where the argument is the usual number of milliseconds since January 1, 1970 00:00:00 in the default time zone. You'll still have to calculate these values of course, but that should be trivial to do with the Calendar class: just take the current date and add or substract x years.

The more attentive reader will notice that the aforementioned setters weren't available until API level 11. If you're targeting that (or newer) platform only, then you're good to go. If you also want to support i.e. Gingerbread devices (Android 2.3 / API level 9+), you can use a backported version of DatePicker in stead.

From here : Set Limit on the DatePickerDialog in Android?

Upvotes: 1

Related Questions