Sid Sid -3 years ago 62
Android Question

How to compare a date string to current date?

I have a date picker through which I am setting up a date in string i.e. mDate.
Now to set up time I want to check if current date and the mDate is same if they are same I want to set minTime to TimePicker dialog and if they are not same min time should not be set to time.

If mDate is empty still time should show all time.

mEditTxt_Time.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Date date = null;
try {

if(!mDate.equals("")) {
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
date = format.parse(mDate);
}

Calendar compareDate = Calendar.getInstance();
compareDate.getTime();

Calendar now = Calendar.getInstance();

TimePickerDialog tpd = TimePickerDialog.newInstance(
PostShippingFragment.this,
now.get(Calendar.HOUR_OF_DAY),
now.get(Calendar.MINUTE),
true
);

if(date!=null) {
if (date.compareTo(compareDate.getTime())) {
tpd.setMinTime(now.get(Calendar.HOUR_OF_DAY), now.get(Calendar.MINUTE), now.get(Calendar.SECOND));
}
}
else {

tpd.setVersion(TimePickerDialog.Version.VERSION_2);

tpd.setAccentColor(ContextCompat.getColor(getActivity(), R.color.colorAccent));

tpd.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialogInterface) {
Log.d("TimePicker", "Dialog was cancelled");
}
});


tpd.show(getFragmentManager(), "Timepickerdialog");
}
}
catch (ParseException e)
{
Log.e("exception",e.toString());

}
}
});


I tried this but I am not able to do the comparison.

Please help. Thank you.

Answer Source

You can use compareTo() method of Date.

It will return an integer value,

  • return a value 0 if the argument Date (compareDate) is equal to this Date;
  • return a value less than 0 if this Date is before the Date argument (compareDate);
  • return a value greater than 0 if this Date is after the Date argument (compareDate).

So, you need to modify your if condition as below, if you want to check both date are same or not.

if (date.compareTo(compareDate.getTime()) == 0) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download