简体   繁体   中英

Compare FileTime and LocalDateTime

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 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.

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.

These are different time structures. You could use toInstant methods to convert them the same type. But LocalDateTime would require timezone. I guess that you just need current system clock time, so instead of LocalDateTime.now() you should use Clock.systemUTC().instant() , so you don't need to convert.

Moreover, if you inject Clock into your code, it will be much easier to mock from unit-tests rather than have dependency on a static methods which give you system time.

My practice when dealing with times, dates, time zones, etc... I usually convert those objects into Unix timestamp and then do needed operations.

long lastModifiedFileTime = Files.getLastModifiedTime(item).toMillis()/1000;
long now = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC);

this would do it, but maybe you should consider using Instant instead of LocalDateTime, stuff gets overly complicated when dealing with time zones(depending on your requirements ofc).

long now = Instant.now().getEpochSecond();

Also you can use Instant objects

Instant now = Instant.now();
Instant lastModifiedFileTime = Files.getLastModifiedTime().toInstant();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM