Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare FileTime and LocalDateTime

Tags:

java

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?

like image 415
Michael Avatar asked May 18 '18 13:05

Michael


People also ask

Can you compare LocalDateTime in Java?

The compareTo() method of LocalDateTime class in Java is used to compare this date-time to the date-time passed as the parameter.

How do I convert FileTime to date?

In Java, we can use DateTimeFormatter to convert the FileTime to other custom date formats.


2 Answers

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.

like image 198
Sneh Avatar answered Oct 12 '22 04:10

Sneh


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.

like image 20
assylias Avatar answered Oct 12 '22 02:10

assylias