How to compare FileTime and LocalDateTime objects in Java?
I want to compare a FileTime object from a file (Files.getLastModifiedTime(item)
) with the current time (LocalDateTime.now()
). But they are not compatible. How can I compare them?
The compareTo() method of LocalDateTime class in Java is used to compare this date-time to the date-time passed as the parameter.
In Java, we can use DateTimeFormatter to convert the FileTime to other custom date formats.
You can get instant from FileTime and create a LocalDateTime object using the instant.
Example
FileTime fileTime = Files.getLastModifiedTime(item);
LocalDateTime now = LocalDateTime.now();
LocalDateTime convertedFileTime = LocalDateTime.ofInstant(fileTime.toInstant(), ZoneId.systemDefault());
Now you can compare now & convertedFileTime.
Remember this is not taking into consideration the timezones which can change.
You can just work with Instant
as well.
The FileTime
API is designed to encourage you to use Instant
rather than LocalDateTime
:
Instant now = Instant.now();
FileTime ft = Files.getLastModifiedTime(item);
if (ft.toInstant().isAfter(now)) { ... }
Note that Instant
makes more sense than LocalDateTime
in this case because it represents a unique instant "in real life". Whereas a LocalDateTime
can be ambiguous, for example during Daylight Saving Time changes.
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