我想要这样的东西:
public class Stream
{
public startTime;
public endTime;
public getDuration()
{
return startTime - endTime;
}
}
同样重要的是,例如,如果startTime是23:00,endTime是1:00,则持续时间为2:00。
为了在Java中实现这一点,应该使用哪些类型?
我想要这样的东西:
public class Stream
{
public startTime;
public endTime;
public getDuration()
{
return startTime - endTime;
}
}
同样重要的是,例如,如果startTime是23:00,endTime是1:00,则持续时间为2:00。
为了在Java中实现这一点,应该使用哪些类型?
当前回答
为了在Java中实现这一点,应该使用哪些类型?
答:长
public class Stream {
public long startTime;
public long endTime;
public long getDuration() {
return endTime - startTime;
}
// I would add
public void start() {
startTime = System.currentTimeMillis();
}
public void stop() {
endTime = System.currentTimeMillis();
}
}
用法:
Stream s = ....
s.start();
// do something for a while
s.stop();
s.getDuration(); // gives the elapsed time in milliseconds.
这是我对你第一个问题的直接回答。
最后一个“注释”,我建议你使用Joda Time。它包含一个适合您需要的间隔类。
其他回答
如果您从System.currentTimeMillis()获取时间戳,那么您的时间变量应该是长变量。
Java提供了静态方法System.currentTimeMillis()。这返回一个长值,所以这是一个很好的参考。很多其他类也接受'timeInMillis'形参,这个形参也很长。
许多人发现使用Joda Time库更容易计算日期和时间。
用这个:
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));
}
(同样重要的是,例如,如果startTime是23:00,endTime是1:00,则持续时间为2:00。)
“else”部分可以得到正确的答案
如果目的只是将粗略的计时信息打印到程序日志中,那么Java项目的简单解决方案不是编写自己的秒表或计时器类,而是使用Apache Commons Lang中的org.apache.commons.lang.time.StopWatch类。
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);
值得注意的是
System.currentTimeMillis() has only millisecond accuracy at best. At worth its can be 16 ms on some windows systems. It has a lower cost that alternatives < 200 ns. System.nanoTime() is only micro-second accurate on most systems and can jump on windows systems by 100 microseconds (i.e sometimes it not as accurate as it appears) Calendar is a very expensive way to calculate time. (i can think of apart from XMLGregorianCalendar) Sometimes its the most appropriate solution but be aware you should only time long intervals.