java - 比较作为文件名一部分的两个文件之间的时间
问题描述
我有 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 分钟的缓冲区,文件名是相同的,我希望能够使用此缓冲区比较它们,我尝试了一些方法,但它没有给我解决方案。
解决方案
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
对象。
链接
- Oracle 教程:日期时间解释如何使用 java.time。
- 维基百科文章:ISO 8601
推荐阅读
- python - “作业”对象在安排事件时没有属性“星期三”错误
- python - sqlite3.OperationalError:不明确的列名:视图
- android - 在显着披露中缺少信息
- plsql - PL SQL Apex_JSON - 解析元素名称
- python-3.x - 谁能建议如何快速抓取这个 https://www3.wipo.int/branddb/en/# 网站?
- loops - 在数据步骤之外循环遍历表的 SAS 方法
- python - 如何设置特定的 x 轴标签以在熊猫箱线图上显示非字母顺序?
- reactjs - 空间与网格:何时使用?
- c# - ListCollections 与 autoizedcollection
- r - 如何将大文件读入R环境