Search code examples
androidandroid-datepickerandroid-date

how to set date for from and to with validation


I am new to android, can any one post the code for the below scenario.

i have to set date for "from" and "to" with validation, that is "to" date should be greater than "from" and "from" date should be lesser than "to" date. is that possiable.

thanks in advance.


Solution

  • try this like :

    public class DatePickerFixedDates extends Activity {    
    
        final Calendar calender = Calendar.getInstance();
        int maxYear = calender.get(Calendar.YEAR);
        int maxMonth = calender.get(Calendar.MONTH);
        int maxDay = calender.get(Calendar.DAY_OF_MONTH);
    
        int minYear = 2004;
        int minMonth = 10; 
        int minDay = 25;
        private Button btn;
        private  DatePicker BirthDateDP;
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.datepickerfixeddates);
            BirthDateDP = (DatePicker) findViewById(R.id.datepicker);
            btn = (Button) findViewById(R.id.button1);        
            btn.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {       
                    int day = BirthDateDP.getDayOfMonth();
                    int month = BirthDateDP.getMonth();
                    int year = BirthDateDP.getYear();           
                }
            });
    
            BirthDateDP.init(maxYear , maxMonth, maxDay, new OnDateChangedListener() {
    
                public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth)
                {           
    
                    if (year < minYear)
                        view.updateDate(minYear, minMonth, minDay);
    
                        if (monthOfYear < minMonth && year == minYear)
                        view.updateDate(minYear, minMonth, minDay);
    
                        if (dayOfMonth < minDay && year == minYear && monthOfYear == minMonth)
                        view.updateDate(minYear, minMonth, minDay);
    
    
                        if (year > maxYear)
                        view.updateDate(maxYear, maxMonth, maxDay);
    
                        if (monthOfYear > maxMonth && year == maxYear)
                        view.updateDate(maxYear, maxMonth, maxDay);
    
                        if (dayOfMonth > maxDay && year == maxYear && monthOfYear == maxMonth)
                        view.updateDate(maxYear, maxMonth, maxDay);
                }
            });        
        }
    
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            getMenuInflater().inflate(R.menu.activity_main, menu);
            return true;
        }
    }