嘿我使用下面的代码来解析不同格式的日期。
trubel是,它采用第一种格式并解析日期,即使它不合适。
public static Date parseDate(String date) {
date = date.replaceAll("[-,.;:_/&()+*# ']", "-");
System.out.print(date);
List<String> formatStrings = Arrays.asList("d-M-y","y-M-d");
for (String formatString : formatStrings) {
try {
System.out.println(new SimpleDateFormat(formatString).parse(date));
return new SimpleDateFormat(formatString).parse(date);
} catch (Exception e) {
}
}
return null;
}
控制台:
1994-02-13
Wed Jul 18 00:00:00 CEST 2018
OR
13-02-1994
Sun Feb 13 00:00:00 CET 1994
所以我不明白为什么第一种格式总是解析?
答案 0 :(得分:2)
你的循环在第一个 public static Date parseDate(String date) {
Date dateToReturn = null;
date = date.replaceAll("[,\\.;:_/&\\(\\)\\+\\*# ']", "-");
String formatString = "d-M-y";
if (date.matches("\\d{4}-\\d{2}-\\d{2}")) {
formatString = "y-M-d";
}
try {
dateToReturn = new SimpleDateFormat(formatString).parse(date);
} catch (Exception e) {
System.out.println("the given date does not math this format " + formatString);
}
return dateToReturn;
}
语句处停止,从你的循环中删除return语句,然后它会在你的日期格式中全部停止。
编辑:根据评论中的要求:
{{1}}
上面我认为你只有两种可能的格式。
答案 1 :(得分:2)
这是jshell中的一个更简单的例子。 “d-M-y”确实解析了两者,因为它默认为宽松。如果您执行setLenient(false)
,则其他格式的日期将会例外。
| Welcome to JShell -- Version 9.0.1
| For an introduction type: /help intro
jshell> java.text.SimpleDateFormat dmy = new java.text.SimpleDateFormat("d-M-y");
dmy ==> java.text.SimpleDateFormat@596ca10
jshell> dmy.parse("13-02-1994")
$2 ==> Sun Feb 13 00:00:00 CST 1994
jshell> dmy.parse("1994-02-13")
$3 ==> Wed Jul 18 00:00:00 CDT 2018
jshell> dmy.isLenient()
$4 ==> true
jshell> dmy.setLenient(false)
jshell> dmy.parse("1994-02-13")
| java.text.ParseException thrown: Unparseable date: "1994-02-13"
| at DateFormat.parse (DateFormat.java:388)
| at (#6:1)
仅供参考,Java 8+ API方法:
jshell> java.time.format.DateTimeFormatter dmy = java.time.format.DateTimeFormatter.ofPattern("dd-MM-yyyy");
dmy ==> Value(DayOfMonth,2)'-'Value(MonthOfYear,2)'-'Value(YearOfEra,4,19,EXCEEDS_PAD)
jshell> java.time.LocalDate.parse("13-02-1994", dmy)
$2 ==> 1994-02-13
jshell> java.time.LocalDate.parse("1994-02-13", dmy)
| java.time.format.DateTimeParseException thrown: Text '1994-02-13' could not be parsed at index 2
| at DateTimeFormatter.parseResolved0 (DateTimeFormatter.java:1988)
| at DateTimeFormatter.parse (DateTimeFormatter.java:1890)
| at LocalDate.parse (LocalDate.java:428)
| at (#3:1)