We want to get a correct dateformat from LOG files generated by different systems with different language and log mechanism.
We thought this can be done be a SimpleDataFormat.parse and try-catch exception way. But the follow code shows a problem.
String tryparseString = "18-01-22 00:03:34:071";
try {
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf1.parse(tryparseString));
System.out.println(sdf1.format(sdf1.parse(tryparseString)));
System.out.println("Yeah! We found a CAN PARSE datefromat = " + sdf1.toPattern());
SimpleDateFormat sdf2 = new SimpleDateFormat("yy-MM-dd HH:mm:ss:SSS");
System.out.println(sdf2.parse(tryparseString));
System.out.println(sdf2.format(sdf2.parse(tryparseString)));
System.out.println("Yeah! We found a CAN PARSE datefromat = " + sdf2.toPattern());
} catch (ParseException e) {
e.printStackTrace();
}
This got a result as:
Sat Jan 22 00:03:34 CST 18
0018-01-22 00:03:34
Yeah! We found a CAN PARSE datefromat = yyyy-MM-dd HH:mm:ss
Mon Jan 22 00:03:34 CST 2018
18-01-22 00:03:34:000
Yeah! We found a CAN PARSE datefromat = yy-MM-dd HH:mm:ss:SSS
So, "18-01-22 00:03:34:071" can both be formatted with yyyy-MM-dd HH:mm:ss and yy-MM-dd HH:mm:ss:SSS.
The former one is far away correct.
So, is there a way to determine a correct dateformat from serveral dateformats?
解决方案
java.time to the rescue.
String[] formats = {
"yyyy-MM-dd HH:mm:ss",
"yy-MM-dd HH:mm:ss:SSS"
};
String tryparseString = "18-01-22 00:03:34:071";
for (String format : formats) {
try {
LocalDateTime.parse(tryparseString, DateTimeFormatter.ofPattern(format));
System.out.println("Yeah! We found a CAN PARSE date format = " + format);
} catch (DateTimeParseException dtpe) {
System.out.println(dtpe);
}
}
This prints:
java.time.format.DateTimeParseException: Text '18-01-22 00:03:34:071' could not be parsed at index 0
Yeah! We found a CAN PARSE datefromat = yy-MM-dd HH:mm:ss:SSS
In other words, the first format, yyyy-MM-dd HH:mm:ss, fails to parse your sample string, and the second succeeds as you wanted it to.
If you still experience a case where a DateTimeFormatter parses a string it shouldn’t, you may try DateTimeFormatter.ofPattern(format).withResolverStyle(ResolverStyle.STRICT). It may catch a few more non-matching strings. In this case you will need uuuu and uu instead of yyyy and yy in the format patterns, though.