我想要这样的东西:
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中实现这一点,应该使用哪些类型?
当前回答
如果您正在编写一个必须处理持续时间的应用程序,那么请查看Joda-Time,它有专门处理持续时间、间隔和周期的类。你的getDuration()方法看起来可以返回一个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);
}
其他回答
如果您从System.currentTimeMillis()获取时间戳,那么您的时间变量应该是长变量。
我发现这段代码在计时时很有用:
public class Et {
public Et() {
reset();
}
public void reset() {
t0=System.nanoTime();
}
public long t0() {
return t0;
}
public long dt() {
return System.nanoTime()-t0();
}
public double etms() {
return etms(dt());
}
@Override public String toString() {
return etms()+" ms.";
}
public static double etms(long dt) {
return dt/1000000.; // 1_000_000. breaks cobertura
}
private Long t0;
}
Java提供了静态方法System.currentTimeMillis()。这返回一个长值,所以这是一个很好的参考。很多其他类也接受'timeInMillis'形参,这个形参也很长。
许多人发现使用Joda Time库更容易计算日期和时间。
如果目的只是将粗略的计时信息打印到程序日志中,那么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);
为了在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。它包含一个适合您需要的间隔类。