Everywhere I looked, they write about before() , after() , compareTo() . But the problem is that I have two buttons and one calendar only.

Here are the clicks of the two buttons:

 public void initButtonListeners(final Date today, final Calendar nextYear) { findViewById(id.linearCalendar).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showCalendarInDialog("Выберите дату выезда", R.layout.calendar_dialog_customized); if (departData == null) { dialogView.init(today, nextYear.getTime()) .withSelectedDate(new Date()); } else { dialogView.init(today, nextYear.getTime()) .withSelectedDate(new Date(departData)); } isFrom = true; } }); findViewById(id.linearArrive).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showCalendarInDialog("Выберите дату приезда", R.layout.calendar_dialog_customized); if (arriveData == null){ dialogView.init(today, nextYear.getTime()) .withSelectedDate(new Date()); } else { dialogView.init(today, nextYear.getTime()) .withSelectedDate(new Date(arriveData)); } isFrom = false; } }); } 

Click on date:

 dialogView.setOnDateSelectedListener(new CalendarPickerView.OnDateSelectedListener() { DateFormat dateFormat = new SimpleDateFormat("dd MMM yyyy"); DateFormat dayOfWeek = new SimpleDateFormat("EEEE"); @Override public void onDateSelected(Date date) { if(isFrom){ departData = dateFormat.format(date); departdOw = dayOfWeek.format(date); tvDepart.setText(departData); tvSubDepart.setText(departdOw); }else{ arriveData = dateFormat.format(date); arrivedOw = dayOfWeek.format(date); tvArrive.setText(arriveData); tvSubArrive.setText(arrivedOw); } theDialog.dismiss(); } }); 

I need to withdraw Toast if I chose a arrival date which is less than the departure date. And tried to compare departDate with arriveDate ... But the error, because they are String type. but there is nothing to compare him.

Question:

How to be in this case, how to compare?

    2 answers 2

    Convert departDate and arriveDate type String into type Date , and then compare.

    Conversion example:

     String departDate = "Sat Jan 03 19:47:23 MSK 1984"; DateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH); Date date = format.parse(departDate); 
    • My formatting is in this form, so it will go, or should you use the formatting exactly? - DevOma
    • @Omuradil, in the example, the date format "EEE MMM dd HH:mm:ss zzz yyyy" used for the string "Sat Jan 03 19:47:23 MSK 1984" . You need to use the format in which your departDate and arriveDate string fields departDate arriveDate . - Arsenicum
    • Thanks, I'll try ... - DevOma

    Dates can be compared using getTime() . For example:

     ............................... Date date1 = new Date(arg1); Date date2 = new Date(arg2); 

    Actually, the comparison example itself:

     boolean b; if (date1.getTime() > date2.getTime()) b = true; else b = false; System.out.println(b);