简体   繁体   中英

How to get last modified and current sysdate time difference in java

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));

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);

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.

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