如果我理解正确,以下(使用 Joda Time)应该会有所帮助
import org.joda.time.DateTime;
import org.joda.time.Period;
private String formatDuration(DateTime dt1, DateTime dt2) {
Period period = new Period(dt1, dt2);
String str = String.format("%s:%02d:%02d:%02d:%02d:%02d",
period.getYears(), period.getMonths(), period.getDays(),
period.getHours(), period.getMinutes(), period.getSeconds());
// Ignoring milliseconds
String[] tokens = str.split(":");
boolean currNonZero = false, flag = false, isFirst = true;
int ctr = 0, pos = 0;
StringBuilder sb = new StringBuilder();
for (String token : tokens) {
pos++;
int val = Integer.parseInt(token);
currNonZero = (val > 0);
if ((ctr < 3 && (flag || currNonZero)) || (ctr == 0 && pos > 3)) {
if (isFirst) { isFirst = false; }
else { sb.append(":"); }
sb.append(token);
flag = (++ctr < 3);
}
}
return sb.toString();
}
几个测试,
DateTime dt1 = new DateTime(2012, 1, 1, 8, 3, 5, 0);
DateTime dt2 = new DateTime(2012, 1, 2, 9, 5, 6, 0);
DateTime dt3 = new DateTime(2012, 2, 3, 11, 3, 5, 0);
DateTime dt4 = new DateTime(2012, 2, 3, 11, 3, 10, 0);
DateTime dt5 = new DateTime(2012, 2, 3, 11, 3, 10, 5); //5 millis away from dt4
formatDuration(dt1, dt2); // Returns "01:01:01"
formatDuration(dt1, dt3); // Returns "01:02:03"
formatDuration(dt3, dt4); // Returns "00:00:05"
formatDuration(dt4, dt5); // Returns "00:00:00"