When comparing dates as strings, you should use SimpleDateFormat("yyyy-MM-dd") . Comparing them using the SimpleDateFormat("dd-MM-yyyy") format SimpleDateFormat("dd-MM-yyyy") will be an error in most cases because of the least significant number that will be checked first, and most importantly, the last. If you must use the dd-MM-yyyy format, then you can write a function that breaks the lines and then compares the year / month / day in the correct order and returns positive, negative, or zero.
// Compares first date to second date and returns an integer // can be used in a similar manner as String.CompareTo() Public Static int CompareDates(String Date1, String Date2) { String[] splitDate1 = Date1.split("-"); String[] splitDate2 = Date2.split("-"); int ret = -1; if (splitDate1[2].CompareTo(splitDate2[2]) == 0) { if (spliDatet1[1].CompareTo(splitDate2[1]) == 0) { if (splitDate1[0].CompareTo(splitDate2[0]) == 0) { ret = 0; } else if (splitDate1[0].CompareTo(splitDate2[0]) > 0) { ret = 1; } } else if (splitDate1[1].CompareTo(splitDate2[1]) > 0) { ret = 1; } } else if (splitDate1[2].CompareTo(splitDate2[2]) > 0) { ret = 1; } Return ret; }
source share