简体   繁体   English

比较java中的卡到期日期。 世纪末?

[英]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.我需要使用Calendar.after()方法将当前日期与格式为MM/yy的卡到期日期进行比较。 (I can't use Java 8 with its new Date processing classes). (我不能将 Java 8 与它的新 Date 处理类一起使用)。

To match years I use SimpleDateFormat.set2DigitYearStart(firstYearOfCurrentCentury) .为了匹配年份,我使用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.所以这工作正常,但假设我的应用程序将在 2099 年使用,因此卡到期日期可能会变成MM/02因此该值将大于当前的 2099 年,但应用程序仍会认为它是 2002 年。

What's the good practice to process this situation, if we don't know card validity terms and the format still MM/yy ?如果我们不知道卡有效期和格式仍然是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.您只需要先比较年份,然后比较月份和比较器,其中 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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