One of the requirements in my project needs to check if the file's creation date and determine if it is older than 2 days from current day. In Java, there is something like below code which can get us the file's creation date and other information.
Path file = ...;
BasicFileAttributes attr = Files.readAttributes(file, BasicFileAttributes.class);
System.out.println("creationTime: " + attr.creationTime());
System.out.println("lastAccessTime: " + attr.lastAccessTime());
System.out.println("lastModifiedTime: " + attr.lastModifiedTime());
But I don't know how to write the same code in Scala. Could anyone let me know how the same can be implemented in Scala.
Java
The preferred way to do this is using the newer java.nio.file
API:
import java.nio.file.*;
You can access the modified time (along with much else) in Files
:
FileTime modified = Files.getLastModifiedTime(path)
This gives you a FileTime
, which may be converted to a java.time.Instant
Instant modifiedInstant = modified.toInstant();
You can then do this, with:
import java.time.temporal.ChronoUnit.DAYS;
boolean isMoreThan2DaysOld = modifiedInstant.plus(2, DAYS).isBefore(Instant.now())
Scala
All of this is accessible from scala (unless you are using ScalaJS):
import java.nio.file._; import java.time._; import java.time.temporal.ChronoUnit.DAYS
val isMoreThan2DaysOld
= Files.getLastModifiedTime(path).toInstant.plus(2, DAYS) isBefore Instant.now
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With