Best way to compare dates in Android

nunos picture nunos · May 27, 2012 · Viewed 184.5k times · Source

I am trying to compare a date in a String format to the current date. This is how I did it (haven't tested, but should work), but am using deprecated methods. Any good suggestion for an alternative? Thanks.

P.S. I really hate doing Date stuff in Java. There are so many ways to do the same thing, that you really aren't sure which one is the correct one, hence my question here.

String valid_until = "1/1/1990";

Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyy");
Date strDate = sdf.parse(valid_until);

int year = strDate.getYear(); // this is deprecated
int month = strDate.getMonth() // this is deprecated
int day = strDate.getDay(); // this is deprecated       

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

Calendar currentDate = Calendar.getInstance();

if (currentDate.after(validDate)) {
    catalog_outdated = 1;
}

Answer

JB Nizet picture JB Nizet · May 27, 2012

Your code could be reduced to

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date strDate = sdf.parse(valid_until);
if (new Date().after(strDate)) {
    catalog_outdated = 1;
}

or

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date strDate = sdf.parse(valid_until);
if (System.currentTimeMillis() > strDate.getTime()) {
    catalog_outdated = 1;
}