2011-02-14 188 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(); 
}