Java 8
好的,这有点令人不愉快,但是可以完成工作,这是使用Java 8的Time API
LocalDateTime dt1 = LocalDateTime.ofInstant(Instant.ofEpochMilli(1429174464829L), ZoneId.systemDefault());
LocalDateTime dt2 = LocalDateTime.now().plusDays(1);
System.out.println(dt1);
System.out.println(dt2);
StringJoiner sj = new StringJoiner(":");
long hours = ChronoUnit.HOURS.between(dt1, dt2);
sj.add(Long.toString(hours));
dt2 = dt2.minusHours(hours);
long mins = ChronoUnit.MINUTES.between(dt1, dt2);
sj.add(Long.toString(mins));
dt2 = dt2.minusMinutes(mins);
long secs = ChronoUnit.SECONDS.between(dt1, dt2);
sj.add(Long.toString(secs));
System.out.println(sj);
并会输出类似…
2015-04-16T18:54:24.829
2015-04-17T14:10:54.281
19:16:29
现在,如果我要做类似的事情…
LocalDateTime dt2 = LocalDateTime.now().plusDays(4);
我会得到91:21:10.
我希望有人有更好的解决方案,因为那有点混乱…
乔达时间
如果您不能使用Java 8,请使用Joda-Time
DateTime dt1 = new DateTime(1429174464829L);
DateTime dt2 = DateTime.now().plusDays(4);
System.out.println(dt1);
System.out.println(dt2);
Duration yourDuration = new Duration(dt1, dt2);
Period period = yourDuration.toPeriod();
PeriodFormatter hms = new PeriodFormatterBuilder()
.printZeroAlways()
.appendHours()
.appendSeparator(":")
.appendMinutes()
.appendSeparator(":")
.appendSeconds()
.toFormatter();
String result = hms.print(period);
System.out.println(result);
输出91:26:33