bharathi bharathi - 7 months ago 18
Java Question

Find the difference between two times in java

I have a search button, when the user clicks the search button the search() method is get called. I need to calculate the how much time it took to display the result to the user as we see in the google search.

This is my code.

SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String strDate;
def startTime() {
Calendar cal = Calendar.getInstance();
System.out.println("Current milliseconds since 13 Oct, 2008 are :"
+ cal.getTimeInMillis());
long startTime=cal.getTimeInMillis();
/*Date startNow = new Date();
strDate = sdfDate.format(startNow);
Date startTime=sdfDate.parse(strDate);
print "startTime"+startTime*/
return startTime;

}
def endTime(){
Calendar cal = Calendar.getInstance();
System.out.println("Current milliseconds :"
+ cal.getTimeInMillis());
long endTime=cal.getTimeInMillis();
/*Date endNow = new Date();
print "endNow"+endNow
strDate = sdfDate.format(endNow);
Date endTime=sdfDate.parse(strDate);
print "endTime"+endTime*/
return endTime;
}

def differenceTime(long startTime,long endTime){
print "requestEndTime"+endTime
print "requestStartTime"+startTime
long timeDifference = endTime - startTime;
return timeDifference;
}


Here I am trying to get the starttime and endtime and trying to calculate the difference. I do know whether the way I implemented is right? Please tell me usually how the time difference is being calculated.

Answer

Instead of using Calendar it's easier to use System.currentTimeMillis():

def startTime() { 
    long startTime=System.currentTimeMillis();
    return  startTime;
}

Calculating time difference based on System.currentTimeMillis() is very common in Java, and you'll doing it right (I mean endTime - startTime)

So, your code could looks like:

long startTime = System.currentTimeMillis();
// .....
// processing request
// .....
long endTime = System.currentTimeMillis();
long differenceTime = endTime - startTime;
log.debug("Request time: " + differenceTime);
//or
log.debug("Request time: " + TimeUnit.MILLISECONDS.toSeconds(differenceTime) + " sec");