java 在java中找到两次之间的差异

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14494569/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 16:27:32  来源:igfitidea点击:

Find the difference between two times in java

javadategrailstimedate-arithmetic

提问by bharathi

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.

我有一个搜索按钮,当用户单击搜索按钮时,将调用 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.

在这里,我试图获取开始时间和结束时间并尝试计算差异。我知道我实施的方式是否正确?请告诉我通常是如何计算时差的。

回答by Igor Artamonov

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

而不是使用Calendar它更容易使用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)

基于 System.currentTimeMillis() 计算时差在 Java 中很常见,你会做对(我的意思是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");

回答by aa8y

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

您可以改用此类。我在学习 Coursera 的算法,第一部分课程时学到了它。

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());
    }
}

回答by Sanjit Kumar Mishra

You can code it like this:

你可以这样编码:

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

回答by Basil Bourque

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.timeframework. See Tutorial. See new methods added to old classes for conversion.

避免使用旧的 java.util.Date/.Calendar 类。在被证明设计不佳且麻烦之后,旧的日期时间类已被java.time框架取代。请参阅教程。请参阅添加到旧类的新方法以进行转换。

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

JSR 310定义。许多 java.time 功能已向后移植到 Java 6 和 7,并进一步适应 Android

Instant

Instant

An Instantrepresents a moment on the timeline in UTCwith a resolution of up to nanoseconds.

AnInstant代表UTC时间线上的一个时刻,分辨率高达纳秒

Capturing the current moment is limited to millisecondsresolution 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).

由于依赖于旧的预先存在的实现,捕获当前时刻仅限于毫秒分辨率Clock;在 Java 9 中被替换为以纳秒为单位捕获当前时刻(取决于您计算机的硬件时钟能力)。

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

Duration

Duration

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

所述Duration类表示一时间跨度为秒的总数目加在纳秒几分之一秒。

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

Output

输出

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

Duration::toString方法使用标准 ISO 8601 格式生成文本表示。以P(表示句点)开头,aT将年-月-日与时-分-秒分开。所以一个半小时将是PT1H30M。这种格式避免了01:30含义经过时间与一天中的时间的歧义。

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.