【问题标题】:SimpleDateFormat.parse("MM/yyyy") [duplicate]SimpleDateFormat.parse("MM/yyyy") [重复]
【发布时间】:2018-03-13 12:48:59
【问题描述】:

我正在尝试实现一种将String 解析为Date 的方法,我想使用SimpleDateFormat,因为这似乎可以完成工作:

java.util.Date parseMonth(String str) throws ParseException {
    SimpleDateFormat format=new SimpleDateFormat("MM/yyyy");
    return format.parse(str);
}

但由于某些原因,我在我希望得到的输入上没有得到 ParseException

  • “00/2000”-> 1999-12-01,没有例外
  • “13/2000”-> 2001-01-01,没有例外

检查String 是否为正确日期的首选方法是什么(对于某些依赖于实现的格式)?

【问题讨论】:

标签: java date simpledateformat date-parsing


【解决方案1】:

SimpleDateFormat 默认情况下是宽松的,因此它会尝试变得聪明(通常会失败)并执行诸如“第 0 个月变成去年 12 月”之类的事情

要使无效输入引发异常,只需禁用宽松行为即可:

SimpleDateFormat format = new SimpleDateFormat("MM/yyyy");
format.setLenient(false); // not lenient

这将为无效输入抛出ParseException,例如00/200013/2000


但现在我们有了更好的 API。从 Java 8 开始,有一个 new date/time API,对于版本 nice backport。在这个 API 中,格式化程序默认是不宽松的:

DateTimeFormatter fmt = DateTimeFormatter.ofPattern("MM/yyyy");
YearMonth.parse("00/2000", fmt); // exception

【讨论】:

  • 为什么投反对票? setLenient不解决问题吗?
  • 我不知道这里是不是这样。但有些用户喜欢对被否决和/或重复问题的答案投反对票,以避免出现太多此类问题。这是一个很好的答案。人们可能仍会争辩说,最好将答案保留在原始问题所在的位置。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-16
  • 1970-01-01
  • 2012-05-05
  • 2016-03-13
  • 1970-01-01
  • 2018-08-11
相关资源
最近更新 更多