Search code examples
javanio2

Get getLastModifiedTime(path) in TimeUnit.Days


I am trying to get the number of days, after the last modification of a given file.

Following code gives me 18135 when checked for a file which is just been modified.

Code

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));
    }
}

The output is just a number -

Output

18135

Please help me get the number of days.


Solution

  • To get the difference between now, you could use:

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

    Note that this may fail if Instant.now() returns a value less than Files.getLastModifiedTime(path).toInstant() which is possible.

    See relevant Duration::between javadoc

    As per @RealSkeptic comment, you may also use the DAYS enum constant from ChronoUnit:

    long days = ChronoUnit.DAYS.between(Files.getLastModifiedTime(path).toInstant(), 
                        Instant.now())
            ;
    

    Note that the warning about failing if Files.getLastModifiedTime(path).toInstant() is greater than Instant.now() does not apply: it will simply return a negative number.