Reputation: 61
I have an API code which writes a token in text file. I required to check last updated time and current system. If the difference is 20 min it will generate a new token.
Problem is I am not getting difference when I use following code. How to get difference for these in minutes in an integer value?
java.nio.file.Path path = Paths.get("C://Users//xxx//token.txt");
attributes = Files.readAttributes(path, BasicFileAttributes.class);
System.out.println("Updated Time : " + attributes.lastModifiedTime());
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date));
Upvotes: 2
Views: 1134
Reputation: 9329
One way of getting difference is to map FileTime
to Instant
, which will allow to create Duration
between two.
import java.time._
path = Paths.get("C://Users//xxx//token.txt");
attributes = Files.readAttributes(path, BasicFileAttributes.class);
lastModifiedTime = attributes.lastModifiedTime().toInstant()
currentTime = Instant.now()
diffInMins = Duration.between(lastModifiedTime, currentTime).toMinutes()
Calling toMinutes()
on Duration
will give back difference between given Instant
s in minutes.
Upvotes: 0
Reputation: 44980
Convert to Instant
and compare using Instant.isAfter()
method. Do not convert to String
, that's only useful when displaying human readable time.
Path path = Paths.get("C://Users//xxx//token.txt");
BasicFileAttributes attributes = Files.readAttributes(path, BasicFileAttributes.class);
Instant deadline = Instant.now().minus(20, ChronoUnit.MINUTES);
boolean itsTime = attributes.lastModifiedTime().toInstant().isAfter(deadline);
Upvotes: 1