为此目的设计的库是更好的方法,但是具有权利的SimpleDateFormat
可能足以满足不到一天的期限。较长的时期需要特别对待这一天。TimeZone
import java.text.DateFormat;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
public class Elapsed {
private static final long MS_DAY = 24 * 60 * 60 * 1000;
private final DateFormat df = new SimpleDateFormat("HH : mm : ss : S");
public Elapsed() {
df.setTimeZone(TimeZone.getTimeZone("GMT"));
}
private String format(long elapsed) {
long day = elapsed / MS_DAY;
StringBuilder sb = new StringBuilder();
sb.append(day);
sb.append(" : ");
sb.append(df.format(new Date(elapsed)));
return sb.toString();
}
public static void main(String[] args) {
Elapsed e = new Elapsed();
for (long t = 0; t < 3 * MS_DAY; t += MS_DAY / 2) {
System.out.println(e.format(t));
}
}
}
控制台输出:
0 : 00 : 00 : 00 : 0
0 : 12 : 00 : 00 : 0
1 : 00 : 00 : 00 : 0
1 : 12 : 00 : 00 : 0
2 : 00 : 00 : 00 : 0
2 : 12 : 00 : 00 : 0