简体   繁体   中英

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.

如果你有卡创建日期这样的数据,你也可以与之比较,认为你有约束卡到期日期>=卡创建日期。

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM