显示java中2个日期之间的小时数

我有这个代码,我只需要显示几小时:min:sec,任何帮助?

String var = "1429174464829"; (this is time in System.currentTimeMillis() ) String p = "HH:mm:ss"; SimpleDateFormat f = new SimpleDateFormat(p); long t = var - System.currentTimeMillis(); String result = f.format(new Date(t)); 

在示例String var中,比System.currentTimeMillis()结果问题高1小时

编辑:我获得:结果= 21:59:00

谢谢

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

有一些时区问题。 我们必须使用SimpleDateFormat指定时区。 在使用标准UTC时区添加系统时区的时差后,它会给出结果。 默认情况下,它占用您的本地系统时区。

 String var = "1429174464829"; (this is time in System.currentTimeMillis() ) String p = "HH:mm:ss"; SimpleDateFormat f = new SimpleDateFormat(p); f.setTimeZone(TimeZone.getTimeZone("UTC")); long t = long.parseLong(var) - System.currentTimeMillis(); String result = f.format(new Date(t)); 

嗯,根据我的经验,这种事情是你不想自己编码的东西。 在某个地方,你会遇到像夏令时,闰年等边境案件等。

如果你想要可靠地做这种事情,请使用像JodaTime这样的时间库(我的偏好)

例如, Period类可以为您提供单独的部分,并且可以通过调用toPeriod()从Duration生成。

我想你可以用Jodatime来获得好几个小时,这是一个很好的图书馆。 希望能帮助到你。 干杯!