在 TimeUnit.Days 中获取 getLastModifiedTime(path)

Get getLastModifiedTime(path) in TimeUnit.Days

我正在尝试获取给定文件最后一次修改后的天数。

检查刚刚修改过的文件时,以下代码给出了 18135

代码

public class IOExamples {
    public static void main(String[] args) throws IOException {
        Path path = Paths.get("zoo.log"); // zoo.log was just been modified
        System.out.println(Files.getLastModifiedTime(path).to(TimeUnit.DAYS));
    }
}

输出只是一个数字 -

输出

18135

请帮我算出天数。

要获得现在之间的差异,您可以使用:

Duration.between(Files.getLastModifiedTime(path).toInstant(), Instant.now())
        .toDays()
        ;

请注意,如果 Instant.now() return 的值可能小于 Files.getLastModifiedTime(path).toInstant(),这可能会失败。

查看相关内容Duration::between javadoc

根据@RealSkeptic 评论,您还可以使用 ChronoUnit:

中的 DAYS 枚举常量
long days = ChronoUnit.DAYS.between(Files.getLastModifiedTime(path).toInstant(), 
                    Instant.now())
        ;

请注意,如果 Files.getLastModifiedTime(path).toInstant() 大于 Instant.now() 则失败的警告不适用:它只是 return 一个负数。