【问题标题】:How to check if the Date conforms to a specific DateFormat without using Exception?如何在不使用异常的情况下检查日期是否符合特定的日期格式?
【发布时间】:2016-02-25 12:08:27
【问题描述】:

我知道 parse() 可用于了解有效日期是否符合特定格式。但这会在失败的情况下引发异常。我只想验证日期是否为特定格式。特别是我需要这个比较的布尔结果。如何在 Java 中实现?

【问题讨论】:

  • 据我所知没有。您需要为自己创建一个使用 parse() 的。如果捕获到异常,则需要返回 false。如果解析成功,返回true。
  • @Prashant 在验证中避免异常是可能的(从 Java 1.0 开始),请参阅我的答案。
  • @Meno Hochschild。正确的!好东西。感谢您指出这一点。

标签: java date simpledateformat


【解决方案1】:

我想知道为什么这里没有人知道使用ParsePosition 遵循标准验证。基于异常逻辑的编程或多或少是邪恶的。

SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
sdf.setLenient(false);
ParsePosition pp = new ParsePosition(0);
java.util.Date d = sdf.parse("02/29/2015", pp);

if (d == null) {
    System.out.println("Error occurred at position: " + pp.getErrorIndex());
    return false;
} else {
    return true; // valid
}

请注意,使用严格模式很重要!

有点超出问题的范围但很有趣:

新的java.time-library (JSR-310) does force the user to code against exceptions - 与“SimpleDateFormat”相比明显回归。捕获异常的问题通常是性能不佳,如果您解析质量较低的批量数据,这可能是相关的。

【讨论】:

    【解决方案2】:

    除非您想编写可以匹配日期格式的正则表达式,否则恐怕除了捕获ParseException 之外别无他法。

    【讨论】:

      【解决方案3】:
      public static Scanner s;
      
      public static void main(String[] args) {
          System.out.println(checkDateFormat("2000-01-01"));
      }
      
      // Checks if the date meets the pattern and returns Boolean
      // FORMAT yyyy-mm-dd RANGE : 2000-01-01 and 2099-12-31
      public static Boolean checkDateFormat(String strDate) {
      
          if (strDate.matches("^(19|20)\\d\\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$")) {
              return true;
          } else {
              return false;
          }
      }
      

      这里的解决方案使用正则表达式模式来验证日期格式(不需要例外,因为不需要任何例外,因为您没有使用 SimpleDateFormat Parse() 方法)。有关正则表达式和日期的更多信息/帮助,请访问http://www.regular-expressions.info/dates.html。

      【讨论】:

      • 谢谢。顺便说一句,我假设范围是从1900-01-01 到2099-12-31,不是吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      • 2021-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多