简单的秒表中的Java getElapsedTime,返回枚举

时间:2014-08-13 22:23:42

标签: java enums stopwatch

我在Java中用一个简单的stopWatch来测量时间。这一类的一种方法是:

public long[] getElapsedTime() { long timestamp; timestamp = (running) ? ((System.currentTimeMillis() / 1000) - (startTime / 1000)) : (((stopTime - startTime) / 1000)); long day = TimeUnit.SECONDS.toDays(timestamp); long hours = TimeUnit.SECONDS.toHours(timestamp) - (day * 24); long minutes = TimeUnit.SECONDS.toMinutes(timestamp) - (TimeUnit.SECONDS.toHours(timestamp) * 60); long seconds = TimeUnit.SECONDS.toSeconds(timestamp) - (TimeUnit.SECONDS.toMinutes(timestamp) * 60); return new long[] {day, hours, minutes, seconds}; }

方法返回一个包含4个成员的数组。但是调用这种方法是如此奇怪:

new Formatter().format("%02d:%02d:%02d", stopwatch.getElapsedTime()[1], stopwatch.getElapsedTime()[2], stopwatch.getElapsedTime()[3] ))

我可以将其作为某些“enum”或更人性化的格式返回吗?我想像这样的实现:

new Formatter().format("%02d:%02d:%02d", stopwatch.getElapsedTime().HOURS, stopwatch.getElapsedTime().MINUTES, stopwatch.getElapsedTime().SECONDS ))

有可能吗?

我知道我可以在类中设置经过的时间单位(类不是静态的)然后为单位设置 getters (例如getDays(),getHours(),getMinutes()和getSeconds ())但我认为这不是我的想象:)

感谢任何提示

2 个答案:

答案 0 :(得分:2)

为什么不创建一个Time课程,让getElapsedTime()返回Time的实例,并使用相应的getterssetters

答案 1 :(得分:-1)

OMG今天我正在努力获得很好的答案!我制作了一些以毫秒为单位的代码,并返回一个完美格式化的String。这是:

public static String getTime(long time){
    long timeToEdit = time;
    String textToDraw = "";
    if(TimeUnit.MILLISECONDS.toMinutes(time) >= 10){
        textToDraw = textToDraw + TimeUnit.MILLISECONDS.toMinutes(time);
    }else{
        textToDraw = textToDraw + "0" + TimeUnit.MILLISECONDS.toMinutes(time);
    }
    timeToEdit -=        TimeUnit.MINUTES.toMillis(TimeUnit.MILLISECONDS.toMinutes(timeToEdit));
    if(TimeUnit.MILLISECONDS.toSeconds(timeToEdit) >= 10){
        textToDraw = textToDraw + ":" + TimeUnit.MILLISECONDS.toSeconds(timeToEdit);
    }else{
        textToDraw = textToDraw + ":0" + TimeUnit.MILLISECONDS.toSeconds(timeToEdit);
    }
    timeToEdit -= TimeUnit.SECONDS.toMillis(TimeUnit.MILLISECONDS.toSeconds(timeToEdit));
    if(TimeUnit.MILLISECONDS.toMillis(timeToEdit) >= 100){
        textToDraw = textToDraw + ":" + TimeUnit.MILLISECONDS.toMillis(timeToEdit);
    }else if(TimeUnit.MILLISECONDS.toMillis(timeToEdit) >= 10) {
        textToDraw = textToDraw + ":0" + TimeUnit.MILLISECONDS.toMillis(timeToEdit);
    }else{
        textToDraw = textToDraw + ":00" + TimeUnit.MILLISECONDS.toMillis(timeToEdit);
    }
    return textToDraw;
} 

例如,如果您运行:

System.out.println(getTime(60000));

将打印

1:00:00