0

I have a date picker dialog, using which user can select a date. Conditions are :

  • Date must not be greater than today (system date)
  • Date must not be older than 3 months

I have done the first bit but I am not sure how to compare two dates to check if it is older than 3 months.

in the code : checkInYear, checkInMonth and checkInDay is what user selected and year, month, day is the system date.

Could you please suggest how to compare two dates to check if it is greater than 3 months.

Your help is much appreciated.

@Override
            public void onDateChanged(DatePicker view, int selectedYear,
                    int selectedMonthOfYear, int selectedDayOfMonth) {
                setCurrentDateOnView();
                int checkInYear = selectedYear;
                int checkInMonth = selectedMonthOfYear;
                int checkInDay = selectedDayOfMonth;                   
                if (checkInYear > year || checkInYear < year) {
                    view.updateDate(year, month, day);

                }

                if (checkInMonth > month && checkInYear == year) {
                    view.updateDate(year, month, day);
                }

                if (checkInDay > day && checkInYear == year
                        && checkInMonth == month) {
                    view.updateDate(year, month, day);
                }



            }
        };

Thank you very much

BRDroid
  • 3,920
  • 8
  • 65
  • 143
  • This post might help http://stackoverflow.com/questions/21285161/android-difference-between-two-dates – stonecompass Aug 31 '15 at 07:42
  • Hi thanks for the response, that link calculates till total number of days, but how do i calculate in months.? – BRDroid Aug 31 '15 at 07:52

1 Answers1

3

Just use according to your need.

String sDate = "05-10-2012"; // suppose you create this type of date as string then

SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");

Date date = sdf.parse(sDate);

Calendar c = Calendar.getInstance();

c.getTime().compareTo(date);

it depending on your string or how you can get? you can get all individually from datepicker then directly set in calendar instance

Calendar my = Calendar.getInstance();
my.set(year, month, day);

now compare

my.compareTo(Calendar.getInstance());

and for less then 3 months you can use something like ..

Date referenceDate = new Date();
Calendar c = Calendar.getInstance(); 
c.setTime(referenceDate); 
c.add(Calendar.MONTH, -3);
return c.getTime();
SRB Bans
  • 3,096
  • 1
  • 10
  • 21