[英]issue in the dd-MM-yyyy format
I am trying to parse date in dd-MM-yyyy and my input is 01-01-2017 it is working fine but when i enter 1-1-2017 or 1-1-17 it is also working but i need only in the format of 01-01-2017 please can any one provide me solution 我正在尝试在dd-MM-yyyy中解析日期,我的输入是01-01-2017,它工作正常,但是当我输入1-1-2017或1-1-17时,它也工作,但是我只需要在2017年1月1日的格式,任何人都可以向我提供解决方案
Thanks in advance 提前致谢
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
formatter.setLenient(false);
String dateInString = "1-01-2013";
try {
Date date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatter.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat
, even with lenient
to false
(that is the more strict mode) is not enough to get a full strict parsing. SimpleDateFormat
,即使lenient
为false
(即更严格的模式)也不足以获得完整的严格解析。
With DateTimeFormatter
Java 8, you could achieve it : 使用
DateTimeFormatter
Java 8,您可以实现它:
String dateInString = "1-01-2013";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MM-yyyy");
try {
LocalDate date = LocalDate.parse(dateInString, dtf);
...
} catch (java.time.format.DateTimeParseException e) {
...
}
For information, ofPattern(String pattern)
uses by default a ResolverStyle
with the java.time.format.ResolverStyle.SMART
value. 对于信息,
ofPattern(String pattern)
默认使用具有java.time.format.ResolverStyle.SMART
值的ResolverStyle
。
In addition to davidxxx's solution, you can also use regex to check :) 除了davidxxx的解决方案之外,您还可以使用正则表达式检查:)
Pattern p = Pattern.compile("\\d{2}-\\d{2}-\\d{4}");
if (!p.matcher(dateInString).matches()) {
// bad date format!
}
Still, I do not understand why you are being so strict. 不过,我不明白您为什么这么严格。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.