Best way to compare dates in Android
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;
}
You can directly create a Calendar
from a Date
:
Calendar validDate = new GregorianCalendar();
validDate.setTime(strDate);
if (Calendar.getInstance().after(validDate)) {
catalog_outdated = 1;
}
You can use compareTo()
CompareTo method must return negative number if current object is less than other object, positive number if current object is greater than other object and zero if both objects are equal to each other.
// Get Current Date Time
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm aa");
String getCurrentDateTime = sdf.format(c.getTime());
String getMyTime="05/19/2016 09:45 PM ";
Log.d("getCurrentDateTime",getCurrentDateTime);
// getCurrentDateTime: 05/23/2016 18:49 PM
if (getCurrentDateTime.compareTo(getMyTime) < 0)
{
}
else
{
Log.d("Return","getMyTime older than getCurrentDateTime ");
}