我创建了在数据导入(40 万条记录)期间解析 View 不同日期格式的方法。我的方法捕获 ParseException 并尝试使用不同的下一种格式解析日期。
问题:在数据导入期间设置正确日期格式的方法是否更好(更快)?
private static final String DMY_DASH_FORMAT = "dd-MM-yyyy";
private static final String DMY_DOT_FORMAT = "dd.MM.yyyy";
private static final String YMD_DASH_FORMAT = "yyyy-MM-dd";
private static final String YMD_DOT_FORMAT = "yyyy.MM.dd";
private static final String SIMPLE_YEAR_FORMAT = "yyyy";
private final List<String> dateFormats = Arrays.asList(YMD_DASH_FORMAT, DMY_DASH_FORMAT,
DMY_DOT_FORMAT, YMD_DOT_FORMAT);
private Date parseDateFromString(String date) throws ParseException {
if (date.equals("0")) {
return null;
}
if (date.length() == 4) {
SimpleDateFormat simpleDF = new SimpleDateFormat(SIMPLE_YEAR_FORMAT);
simpleDF.setLenient(false);
return new Date(simpleDF.parse(date).getTime());
}
for (String format : dateFormats) {
SimpleDateFormat simpleDF = new SimpleDateFormat(format);
try {
return new Date(simpleDF.parse(date).getTime());
} catch (ParseException exception) {
}
}
throw new ParseException("Unknown date format", 0);
}
最佳答案
如果您正在运行单线程,一个明显的改进是创建 SimpleDateFormat
对象只有一次。在多线程情况下使用 ThreadLocal<SimpleDateFormat>
将是必需的。
同时修复异常处理。看起来它是由不应该被信任导入任何数据的人编写的。
关于java - 导入数据时解析日期格式的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39597959/