Java 如何检查给定的字符串是否具有特定的日期格式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18180520/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 23:04:22  来源:igfitidea点击:

How to check if given string is of specific date format?

javagwt

提问by

I want to check if a given string is in a particular dateformat. If not user should be able to throw error message.

我想检查给定的字符串是否采用特定的日期格式。如果不是,用户应该能够抛出错误消息。

DateTimeFormat format=DateTimeFormat.getFormat("yyyy-MM-dd");               
Date d= format.parse("1990-10-");

with this input , it should give error. I tried with try and catch , but its not throwing any exception.

有了这个输入,它应该会出错。我尝试过 try 和 catch ,但它没有抛出任何异常。

回答by Radek Wroblewski

Use java.text.SimpleDateFormat, it throws ParseException.

使用 java.text.SimpleDateFormat,它会抛出 ParseException。

SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");               
try {
  Date d= format.parse("1990-10-");
} catch (ParseException e) {
 ...
}