Java的日期与不同的格式使用下面的代码来解析不同格式的日期
嘿林。Java的日期与不同的格式使用下面的代码来解析不同格式的日期
的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
所以我不明白为什么第一格式解析永诺?
这里是一个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 ==> [email protected]
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的API 8+办法做到这一点:
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)
坦克你那是一个相当不错的答案:) –
我肯定推荐Java 8方式。感谢您提供这个。 –
你的循环停在第一个return
声明,从你的循环中删除return语句,那么它将LOPP在你的日期格式。
编辑:的要求,在意见:
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;
}
这里上面我认为你只有两个可能的格式。
我想返回一个Date,但是如果有异常,它应该执行返回操作吗? –
还行,但基于哪种格式? ,因为有两种格式困惑我 –
好,我用这个在网络后台,我可以在不同的格式从浏览器 –
因为你解析字符串。不格式化 – Jay