2011-02-14 130 views
1

我正在尝试编写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"); 

     } 
} 

回答

3

你真的需要存储时间戳为一个字符串?我建议使用long,例如调用System.currentTimeMills() ...的结果...然后将其格式化为仅用于诊断目的的字符串。比较long值很容易:)

或者,使用Joda Time并保留时间戳为Instant值。这将使格式化更容易,您可以使用isAfter,isAfterNow等进行比较。

0

您从不想使用String来存储/处理精确的日期。

通常要使用DateCalendar甚至更​​现代的Java日期/时间API如约达时间或JSR-310reference implementation here)。

如果你只是想用简单的本地时间戳,然后long可能就足够了:

long currentTime = System.currentTimeMillis(); 

一个long的好处是,你可以使用所有的正常操作(加法,减法,平等检查,小于检查)与使用任何其他数字基元类型所做的操作相同。

0

只是Simplyfying你的方法返回长

public long getCurrentUtcTimestamp() 
{ 
    TimeZone utc = TimeZone.getTimeZone("UTC"); 
    Calendar calendar = Calendar.getInstance(utc); 
    return calendar.getTimeInMillis(); 
}