Dmitry Smolyaninov Dmitry Smolyaninov - 1 month ago 12
Android Question

Compare card expiry date in java. End of century?

I need to compare current date with the card expiry date in format

MM/yy
using
Calendar.after()
method. (I can't use Java 8 with its new Date processing classes).

To match years I use
SimpleDateFormat.set2DigitYearStart(firstYearOfCurrentCentury)
.

So this works fine, but lets suppose my app will be in use in 2099, so card expiry date could turn into
MM/02
so this value will be greater then current 2099 year, but the app will still think it's 2002.

What's the good practice to process this situation, if we don't know card validity terms and the format still
MM/yy
?

Thanks in advance for answer.

Answer

I found the solution in comparing not dates, but Strings lexicographically. You just need to compare year first, then months and impelent Comparator where 0 > 9.

public static boolean compareCardExpDateLexicographically(String dateToCompare) {
    SimpleDateFormat sdf = new SimpleDateFormat("yy/MM", Locale.US);
    Date date = new Date();
    String currentDate = sdf.format(date);
    String dateToComp = sdf.format((parseCardExpiryDate(dateToCompare)).getTime());

    Comparator<String> comp = new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {

            if (o1.compareTo(o2) == 9) return -1;
            else if (o1.compareTo(o2) == -9) return 1;
            else if (o1.compareTo(o2) > 0) return 1;
            else if (o1.compareTo(o2) == 0) return 0;
            else return -1;
        }
    };

    return comp.compare(dateToComp, currentDate) >= 0;
}