开发者

Timestamp calculation function

I am trying to write Java code as a part of my project to get current time for a process and then i need to add a fixed timeout period to it. This new time has to be compared with my above currenttime and take decision based on that. I am not able to add time to th开发者_如何学编程e currenttime and compare it. Can anyone help me by suggesting a way?

This is my code:

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

        }
 }


Do you really need to store the timestamp as a string? I would suggest using a long, e.g. the result of calling System.currentTimeMills()... then format that into a string only for diagnostic purposes. Comparing long values is very easy :)

Alternatively, use Joda Time and keep the timestamps as Instant values. That will make formatting easier, and you can use isAfter, isAfterNow etc for comparisons.


You never want to use String to store/handle precise dates.

Usually you want to use Date, Calendar or even a more modern Java Date/Time API such as Joda Time or JSR-310 (reference implementation here).

If you simply want to use simple local timestamps, then a long might be sufficient:

long currentTime = System.currentTimeMillis();

The advantage of a long is that you can use all the normal operations (addition, subtraction, equality checks, less-than-check) as you would do with any other numeric primitive type.


Just Simplyfying your method returning long

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜