2

I want to check if the file creation is older than a certain time (days). So far, this is how i got the file creation time.

BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class);
long fileCreationTime = attr.creationTime().toMillis();

now I want to check if this file was created before X number of days or not. How would i go about it. I am trying to look into LocalDateTime but kind a lost.

P.S: I don't want to use any external library.

Em Ae
  • 8,167
  • 27
  • 95
  • 162
  • 1
    What's confusing you about `LocalDateTime`? – Sotirios Delimanolis May 26 '16 at 16:20
  • 1
    Something like this? http://stackoverflow.com/questions/32904886/java-util-date-calculate-difference-in-day or this http://stackoverflow.com/questions/1555262/calculating-the-difference-between-two-java-date-instances? – Tunaki May 26 '16 at 16:20

1 Answers1

2

Try this:

long numberOfDays = 5L;
if (attr.creationTime().toInstant().isBefore(
        Instant.now().minus(numberOfDays, ChronoUnit.DAYS)
    )
) {
    // do something
}

If you want to check if the file is older than X number of months, you can proceed as next:

LocalDateTime dt = LocalDateTime.now();
ZonedDateTime zdt = dt.atZone(ZoneId.systemDefault());
long numberOfMonths = 5L;
if (attr.creationTime().toInstant().isBefore(
        dt.minus(numberOfMonths, ChronoUnit.MONTHS).toInstant(zdt.getOffset())
    )
) {
    // do something
}
Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122