java - 导入数据期间解析日期格式的最佳方法

标签 java date parsing date-format

我创建了在数据导入期间解析 View 不同日期格式的方法(400 K 记录)。我的方法捕获 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/

相关文章:

java - EMMA 代码覆盖率报告使用的颜色图例

java - 使用循环语句除以两个数

php - 使用 strtotime() 和 date() 更改日期时间格式时导致特定日期时间的空值

Java TextField 日期自动填充

java - Calendar.getInstance() 的奇怪问题

php - 如何查询这个时间窗口?

python - python 中的 XML 解析 : expaterror not well-formed

parsing - 给定重复的部分,如何使用 Powershell 查找符合特定条件的部分

java - Jsoup 获取动态生成的HTML

java - 游戏可以在 netbeans 上运行,但不能在 jar 文件中的 netbeans 之外运行?