【发布时间】: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 是否为正确日期的首选方法是什么(对于某些依赖于实现的格式)?
【问题讨论】:
-
这里已经回答了这个问题:stackoverflow.com/questions/20231539/…
-
每个人都有自己的方式我更喜欢正则表达式验证器。
-
我建议你避免使用
SimpleDateFormat。它不仅过时了,而且出了名的麻烦。而是使用java.time, the modern Java date and time API。与它一起工作要好得多。查看它的YearMonth和DateTimeFormatter类。 -
重复:How to parse date with only month and year。请参阅 Andreas 使用
YearMonth类编写的 correct Answer。
标签: java date simpledateformat date-parsing