首页 > 解决方案 > 比较作为文件名一部分的两个文件之间的时间

问题描述

我有 2 个文件的时间戳不同

command_step_output/2019/02/13/ea768d46-85bb-4833-8326-fb6be6d60a89_20190213_105228_command_step_output.csv.gz

command_step_output/2019/02/13/ea768d46-85bb-4833-8326-fb6be6d60a89_20190213_105325_command_step_output.csv.gz

它们之间的唯一区别是文件名结束前的时间是不同的 105228(表示 10:52:28)和 105325(表示 10:53:25),我希望能够比较它们并在此示例中使用此逻辑给它一个少 1 分钟或多 1 分钟的缓冲区,文件名是相同的,我希望能够使用此缓冲区比较它们,我尝试了一些方法,但它没有给我解决方案。

标签: javastringlistfiledate

解决方案


java.time

要计算两条路径中的时间差:

    String onePath     = "command_step_output/2019/02/13/ea768d46-85bb-4833-8326-fb6be6d60a89_20190213_105228_command_step_output.csv.gz";
    String anotherPath = "command_step_output/2019/02/13/ea768d46-85bb-4833-8326-fb6be6d60a89_20190213_105325_command_step_output.csv.gz";

    LocalDateTime oneTime = extractDateTime(onePath);
    LocalDateTime anboherTime = extractDateTime(anotherPath);

    Duration diff = Duration.between(oneTime, anboherTime);
    diff = diff.abs();

最后一行中的调用abs将任何负差异转换为正差异,确保缓冲区少 1 分钟和多 1 分钟。extractDateTime在这个答案的底部。要知道差异是否小于一分钟,有不同的方法,我想向您展示几个选项。先说简单的:

    if (diff.toMinutes() < 1) {
        System.out.println("Within the window: " + diff);
    }

窗内:PT57S

我已经打印了消息中的差异,它看起来有点有趣。格式为 ISO 8601。读作“57 秒的时间段”。

上面的缺点是它只能工作整分钟。如果有一天您想将缓冲区更改为 45 秒或 1 分 30 秒怎么办?以下是更一般的:

    Duration buffer = Duration.ofMinutes(1);
    if (diff.compareTo(buffer) < 0) {
        System.out.println("Within the window: " + diff);
    }

我本来希望Duration有一个isShorterThan方法,但它没有。如果您发现代码compareTo难以阅读,那么您并不孤单。另一种方法是减去并查看结果是否为负:

    if (diff.minus(buffer).isNegative()) {
        System.out.println("Within the window: " + diff);
    }

我答应你辅助方法的代码:

private static LocalDateTime extractDateTime(String path) {
    String dateTimeString = path.replaceFirst("^.*/[0-9a-f-]+_(\\d+_\\d+)_command_step_output\\.csv\\.gz$", "$1");
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuuMMdd_HHmmss"); 
    return LocalDateTime.parse(dateTimeString, formatter);
}

我正在使用replaceFirst一个正则表达式来提取20190213_105228零件。然后将其解析为一个LocalDateTime对象。

链接


推荐阅读