Find the difference between two times in java

安稳与你 提交于 2019-12-21 22:59:58

问题


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.


回答1:


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



回答2:


You can use this class instead. I learnt it while pursuing Coursera's Algorithms, Part I class.

public class StopWatch {

    /* Private Instance Variables */
    /** Stores the start time when an object of the StopWatch class is initialized. */
    private long startTime;

    /**
     * Custom constructor which initializes the {@link #startTime} parameter.
     */
    public StopWatch() {
        startTime = System.currentTimeMillis();
    }

    /**
     * Gets the elapsed time (in seconds) since the time the object of StopWatch was initialized.
     * 
     * @return Elapsed time in seconds.
     */
    public double getElapsedTime() {
        long endTime = System.currentTimeMillis();
        return (double) (endTime - startTime) / (1000);
    }
}

The test can be done as:

public class SWTest {

    public static void main(String[] args) throws InterruptedException {
        StopWatch stopWatch = new StopWatch();

        Thread.sleep(10000);
        System.out.println(stopWatch.getElapsedTime());
        Thread.sleep(60000);
        System.out.println(stopWatch.getElapsedTime());
    }
}



回答3:


You can code it like this:

LocalDateTime startTIme = LocalDateTime.now();
//Code Here
LocalDateTime endTime = LocalDateTime.now();
System.out.println(Duration.between(startTIme,endTime));



回答4:


java.time

Avoid the old legacy java.util.Date/.Calendar classes. After proving to be poorly designed and troublesome, the old date-time classes have been supplanted by the java.time framework. See Tutorial. See new methods added to old classes for conversion.

Defined by JSR 310. Much of java.time functionality has been back-ported to Java 6 & 7, and further adapted to Android.

Instant

An Instant represents a moment on the timeline in UTC with a resolution of up to nanoseconds.

Capturing the current moment is limited to milliseconds resolution because of reliance on an old pre-existing implementation of Clock; replaced in Java 9 to capture current moment in nanoseconds (depending on your computer’s hardware clock capability).

Instant start = Instant.now();
…
Instant stop = Instant.now();

Duration

The Duration class represents a span of time as a total number of seconds plus a fraction of a second in nanoseconds.

Duration duration = Duration.between( start , stop );

Output

The Duration::toString method generates a textual representation using the standard ISO 8601 format. Begins with a P (for period), and a T separates years-months-days from hours-minutes-seconds. So an hour and a half would be PT1H30M. This format avoids the ambiguity of 01:30 meaning elapsed time versus time-of-day.

String output = duration.toString();

Alternatively, you can ask for the total number of whole seconds and the total number of nanoseconds.

long seconds = duration.getSeconds();  // Whole seconds.
int nanoseconds = duration.getNano();  // Fraction of a second, maximum of 999,999,999. 


来源:https://stackoverflow.com/questions/14494569/find-the-difference-between-two-times-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!