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

故事扮演 提交于 2019-12-01 01:29:27

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.

protected boolean checkDateValidity(Date date){
        Calendar cal = new GregorianCalendar(date.getYear() + 1900, date.getMonth(), date.getDate(), date.getHours(), date.getMinutes());
        if((cal.getTimeInMillis()-System.currentTimeMillis()) <= 0){
            return false;
        }else{
            return true;
        }
    }

pass the date object to this method

if it returns false means you will show alert message

The code gets the user date from date picker and converting to java date format and storing the date in date format variable and then i'm getting the current system date and storing the date in another date format variable, now i got two date where i can easily compare.

DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
    @Override
   public void onDateSet(DatePicker view, int myear, int monthOfYear,int dayOfMonth) {
// get the user picked date from date picker 
        year=myear;         
        month=monthOfYear+1;
        day=dayOfMonth; 
// then convert all values to a single string
        SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
        String sday = (""+day);
        String smonth=("-"+month);
        String syear=("-"+year);
        String y=(""+sday+smonth+syear);
//convert the string date to a java date             
                    try 
        {
            Date pickerdate = formatter.parse(y);

        } catch (ParseException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
//printing the system current date and picker date
       Date systemdate = new Date(System.currentTimeMillis());
       System.out.println("current "+systemdate);

       System.out.println("format"+pickerdate);

//now u got the two date in date type to compare it easily put ur if and else condition

                   if(your comparedate condition)
                    {
                         do what U want to do
                    }
                   else
                    {

                    }
         }
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!