java时间戳计算函数
我试图将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");
}
}
# 1 楼答案
您永远不想使用
String
来存储/处理精确的日期通常,您希望使用
Date
、Calendar
甚至更现代的Java日期/时间API,如Joda Time或JSR-310(reference implementation here)如果您只是想使用简单的本地时间戳,那么
long
就足够了:long
的优点是,您可以像使用任何其他数字基元类型一样使用所有常规操作(加法、减法、相等检查、小于检查)# 2 楼答案
只是简单化你的方法返回长
# 3 楼答案
您真的需要将时间戳存储为字符串吗?我建议使用
long
,例如调用System.currentTimeMills()
的结果。。。然后将其格式化为字符串,仅用于诊断目的。比较long
值非常容易:)或者,使用Joda Time并将时间戳保留为^{} 值。这将使格式化更容易,并且您可以使用
isAfter
、isAfterNow
等进行比较