Em Ae
Em Ae

Reputation: 8704

Current file is older than a X time or not

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.

Upvotes: 2

Views: 254

Answers (1)

Nicolas Filotto
Nicolas Filotto

Reputation: 44965

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
}

Upvotes: 2

Related Questions