Find Time Differnce

2019-06-10 07:15发布

I want to find time difference in java so that I can create new session if session expires else will asign new time.

标签: java time
3条回答
祖国的老花朵
2楼-- · 2019-06-10 07:31
Returns Time Diffrence in Seconds :




long elapsed_time = 0L;
    java.util.Date startTime = null;
    java.util.Date endTime = null;
    double fsec = 0L;
    String rSec = "";   

        startTime = new java.util.Date();

        <--------Some Operation----->

        endTime = new java.util.Date();
        elapsed_time = endTime.getTime() - startTime.getTime();
        fsec = (elapsed_time) / 1000.00;
        rSec = Double.toString(fsec);
        rSec = rSec + " Sec";
查看更多
手持菜刀,她持情操
3楼-- · 2019-06-10 07:45

You can use System.currentTimeMillis(); to get the current system time in Java (in milliseconds since 01-01-1970 00:00:00 GMT).

The session object most likely also has a method to get the time when the session was last used (look it up in the API documentation of whatever session object you're using).

Subtract the current time from that time from the session and you know how long it has been since the session was last used. If it is longer than the timeout period, do whatever you have to do.

Note that servlet containers have a built-in mechanism for invalidating sessions, you don't need to invalidate sessions manually. Also, HttpRequest.getSession() will automatically create a new HttpSession object for you if there is no session.

查看更多
劫难
4楼-- · 2019-06-10 07:52

Using Date means creating an object which isn't need as it just wraps System.currentTimeMillis() Unfortunately this function is only accurate to a milli-second at best and about 16 ms on some windows systems.

A better approach is to use System.nanoTime() On Oracle's JVM, on Windows XP - 7, Solaris and on recent versions of Linux, this is accurate to better than 1 micro-second. It doesn't create any objects.

long start = System.nanoTime();
// do something.
long time = System.nanoTime() - start; // time in nano-seconds.
// time in seconds to three decimal places
String timeTaken = time/1000000/1e3 + " seconds"; 
查看更多
登录 后发表回答