0

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.

Sunil
  • 429
  • 1
  • 9
  • 25
  • 2
    You get the number of days since the epoch this way. What you need is to subtract the last modified time from the current time and then express the *difference* in days. – RealSkeptic Aug 27 '19 at 16:47

1 Answers1

2

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.

NoDataFound
  • 11,381
  • 33
  • 59