Capattax Capattax - 1 year ago 215
Java Question

Comparing dates in MMYY format

So I am making a Java program that processes a user's fake credit card and I am trying to make an expiration verification conditional statement. However, when I run my program, I get a "String cannot be converted to int" error. I would like to know how should I use the current month and year to check if the date entered by the user has actually expired.

do {
System.out.print("Enter the expiration date mmyy: ");
expiration = expnum.nextInt();

DateFormat dateformat = new SimpleDateFormat("MMyy");
Date date = new Date();
int currentdate = dateformat.format(date);

if (currentdate <= expiration)
check = check + 1;
check = 1;
} while (check == 1);

Answer Source

While @ManoDestra's solution will work, I would prefer to keep the types/data sensible. Thus, rather than convert the existing date into a int (which is kind of nonsensical, and the format followed by parse feels nasty), I would prefer to parse the expiration into a date and then compare directly. Something like this:

expiration = expnum.nextInt();
DateFormat dateformat = new SimpleDateFormat("MMyy");
Date expiryDate = dateFormat.parse(expiration);

Date currentDate = new Date();

if (currentDate.isAfter(expiryDate)) {
   // card has expired
} else {
   // card is still active

You'll probably need to tweak this depending on when you think the expiry actually happens. If the expiry is specified as "0816" is that 01-Aug-2016 00:00:00.000, or 31-Aug-2016 23:59:59.999, or some point in between?

It's a call you have to make (probably by looking at the credit card spec), but that's another thing this approach has compared to the int-converting one: it's not just an abstract sense of "using proper types", but it translates to the real world too. By converting the expiration string to a Date, you need to think about exactly what instant in time that represents, and exactly which values of "now" should count as expired and which should not.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download