Lohit
Lohit

Reputation: 891

Find Time Difference

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

Upvotes: 0

Views: 343

Answers (3)

Peter Lawrey
Peter Lawrey

Reputation: 533880

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

Upvotes: 2

Warrior
Warrior

Reputation: 3304

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

Upvotes: 3

Jesper
Jesper

Reputation: 207006

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.

Upvotes: 3

Related Questions