我有这段代码,我只需要显示小时:分钟:秒,有什么帮助吗?
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
关于java - 在java中显示两个日期之间的小时数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29664907/