How do I measure time elapsed in Java? [duplicate]

2018-12-31 04:25发布

I want to have something like this:

public class Stream
{
    public startTime;
    public endTime;

    public getDuration()
    {
        return startTime - endTime;
    }
}

Also it is important that for example if the startTime it's 23:00 and endTime 1:00 to get a duration of 2:00.

Which types to use in order to accomplish this in Java?

标签: java time
15条回答
梦该遗忘
2楼-- · 2018-12-31 04:34

If you are writing an application that must deal with durations of time, then please take a look at Joda-Time which has class specifically for handling Durations, Intervals, and Periods. Your getDuration() method looks like it could return a Joda-Time Interval:

DateTime start = new DateTime(2004, 12, 25, 0, 0, 0, 0);
DateTime end = new DateTime(2005, 1, 1, 0, 0, 0, 0);

public Interval getInterval() {
    Interval interval = new Interval(start, end);
}
查看更多
高级女魔头
3楼-- · 2018-12-31 04:34

If you prefer using Java's Calendar API you can try this,

Date startingTime = Calendar.getInstance().getTime();
//later on
Date now = Calendar.getInstance().getTime();
long timeElapsed = now.getTime() - startingTime.getTime();
查看更多
刘海飞了
4楼-- · 2018-12-31 04:35

Java provides the static method System.currentTimeMillis(). And that's returning a long value, so it's a good reference. A lot of other classes accept a 'timeInMillis' parameter which is long as well.

And a lot of people find it easier to use the Joda Time library to do calculations on dates and times.

查看更多
公子世无双
5楼-- · 2018-12-31 04:37

If the purpose is to simply print coarse timing information to your program logs, then the easy solution for Java projects is not to write your own stopwatch or timer classes, but just use the org.apache.commons.lang.time.StopWatch class that is part of Apache Commons Lang.

final StopWatch stopwatch = new StopWatch();
stopwatch.start();
LOGGER.debug("Starting long calculations: {}", stopwatch);
...
LOGGER.debug("Time after key part of calcuation: {}", stopwatch);
...
LOGGER.debug("Finished calculating {}", stopwatch);
查看更多
无与为乐者.
6楼-- · 2018-12-31 04:41

If you're getting your timestamps from System.currentTimeMillis(), then your time variables should be longs.

查看更多
初与友歌
7楼-- · 2018-12-31 04:42

Use this:

SimpleDateFormat format = new SimpleDateFormat("HH:mm");

Date d1 = format.parse(strStartTime);
Date d2 = format.parse(strEndTime);

long diff = d2.getTime() - d1.getTime();
long diffSeconds,diffMinutes,diffHours;

if (diff > 0) {
diffSeconds = diff / 1000 % 60;
diffMinutes = diff / (60 * 1000) % 60;
diffHours = diff / (60 * 60 * 1000);
}
else{
long diffpos = (24*((60 * 60 * 1000))) + diff;
diffSeconds = diffpos / 1000 % 60;
diffMinutes = diffpos / (60 * 1000) % 60;
diffHours = (diffpos / (60 * 60 * 1000));
}

(Also it is important that for example if the startTime it's 23:00 and endTime 1:00 to get a duration of 2:00.)

the "else" part can get it correct

查看更多
登录 后发表回答