java 日期相差小时数_在Java中显示2个日期之间的小时数

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java 比较两个时间相差的秒数可以使用 Java 8 的 `Duration` 类或者 `ChronoUnit` 枚举类。 1. 使用 Duration 类 使用 Duration 类可以方便地计算两个时间之间时间差,并且可以将时间差表示成各种时间单位,例如秒、分钟、小时、天等。 以下是比较两个时间相差的秒数的示例代码: ```java import java.time.Duration; import java.time.LocalDateTime; public class TimeDifferenceExample { public static void main(String[] args) { LocalDateTime start = LocalDateTime.of(2022, 1, 1, 0, 0, 0); LocalDateTime end = LocalDateTime.now(); Duration duration = Duration.between(start, end); long seconds = duration.getSeconds(); System.out.println("时间差:" + seconds + " 秒"); } } ``` 在上面的示例代码,我们首先创建了开始时间和结束时间,然后使用 `Duration.between` 方法计算时间差并将其转换为秒数。 2. 使用 ChronoUnit 枚举类 除了使用 Duration 类之外,我们还可以使用 ChronoUnit 枚举类来计算两个时间之间时间差。 以下是比较两个时间相差的秒数的示例代码: ```java import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; public class TimeDifferenceExample { public static void main(String[] args) { LocalDateTime start = LocalDateTime.of(2022, 1, 1, 0, 0, 0); LocalDateTime end = LocalDateTime.now(); long seconds = ChronoUnit.SECONDS.between(start, end); System.out.println("时间差:" + seconds + " 秒"); } } ``` 在上面的示例代码,我们使用 `ChronoUnit.SECONDS.between` 方法计算时间差并将其转换为秒数。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值