在java中找到两次的区别 [英] Find the difference between two times in java
问题描述
我有一个搜索按钮,当用户点击搜索按钮时,search()方法被调用。我需要计算在Google搜索中看到的结果向用户显示的时间。
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.
这是我的代码。
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.
推荐答案
而不是使用日历
它更容易使用 System.currentTimeMillis()
:
Instead of using Calendar
it's easier to use System.currentTimeMillis()
:
def startTime() {
long startTime=System.currentTimeMillis();
return startTime;
}
基于System.currentTimeMillis()计算时差在Java中非常常见,你会做正确的(我的意思是 endTime - 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");
这篇关于在java中找到两次的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!