我正在尝试将 Java 代码编写为项目的一部分,以获取进程的当前时间,然后我需要为其添加固定的超时时间。这个新时间必须与我上面的当前时间进行比较,并据此做出决定。我无法将时间添加到当前时间并进行比较。任何人都可以通过建议的方式帮助我吗?
这是我的代码:
public class SessionDetails
{
public String getCurrentUtcTimestamp() {
TimeZone timeZone = TimeZone.getTimeZone("UTC:00");
DateFormat dateFormat = DateFormat.getDateTimeInstance();
dateFormat.setTimeZone(timeZone);
timeStamp = dateFormat.format(new Date());
return timeStamp;
}
public void createSession()
{
int value = getsession();
String timeStamp = getCurrentUtcTimestamp() ;
System.out.println("New session Details :");
System.out.println("session value:" + value);
System.out.println("Time of creation :" + timeStamp );
}
public boolean checkTimeout(int value)
{
private static long c_Timeout = 10000;
String currentTime = getCurrentUtcTimestamp() ;
if ( currentTime > timeStamp + c_Timeout ) //failing to implement this logic efficiently .please do suggest a way.Thanku..
System.out.println("Sorry TimeOut");
else
System.out.println("Welcome");
}
}
最佳答案
您真的需要将时间戳存储为字符串吗?我建议使用 long
,例如调用 System.currentTimeMills()
的结果......然后将其格式化为仅用于诊断目的的字符串。比较 long
值非常容易:)
或者,使用 Joda Time并将时间戳保持为 Instant
值。这将使格式化更容易,您可以使用 isAfter
、isAfterNow
等进行比较。
关于java - 时间戳计算函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4991296/