以MMYY格式比较日期 [英] Comparing dates in MMYY format

查看:275
本文介绍了以MMYY格式比较日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在制作一个处理用户假信用卡的Java程序,并试图制作一个到期验证条件语句。但是,当我运行程序时,出现无法将字符串转换为int错误。我想知道如何使用当前的月份和年份来检查用户输入的日期是否实际过期。

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();
  System.out.println(dateformat.format(date));
  int currentdate = dateformat.format(date);

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


推荐答案

虽然@ManoDestra的解决方案有效,但我希望保持类型/数据合理。因此,与其将现有的日期转换成 int (这是荒谬的,而且将格式后面跟着 parse 令人讨厌),我希望将到期日期解析为一个日期,然后直接进行比较。像这样的东西:

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
}

您可能需要根据认为到期实际发生的时间进行调整。如果将到期时间指定为 0816,则表示 2016年8月1日00:00:00.000 2016年8月31日23:59 :59.999 ,或介于两者之间?

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?

这是您必须拨打的电话(可能是通过查看信用卡规格而定),但是与进行int转换的方法相比,这是另一回事:它不仅是使用适当类型的抽象含义,而且还转换为现实世界。通过将到期字符串转换为 Date ,您需要仔细考虑确切的时间表示什么时刻以及 now的确切值应该算作过期,而不应该算作过期。

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.

这篇关于以MMYY格式比较日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆