英文:
How to calculate minutes difference between two times
问题
以下是翻译好的部分:
如何计算仅两个时间之间的分钟差异,假设我们有两个时间(在Java中为LocalTime)。
- onDutyTime = 08:00
- offDutyTime = 14:30
为了获得小时差异,我使用了 onDutyTime.until(offDutyTime, ChronoUnit.HOURS)
,这给了我正确的结果,即6小时。但如何获取这两个时间之间的分钟差异(30分钟),或者是否有其他方法可以获得完整的时间差异6小时30分钟。
英文:
How to calculate difference between minutes of two times only, let's suppose we have two times (LocalTime in java).
- onDutyTime = 08:00
- offDutyTime = 14:30
to get hour's difference i used onDutyTime.until(offDutyTime, ChronoUnit.HOURS)
which give me correct result of 6 hours. But how to get minutes difference (30) between these two times minutes.OR there is any other way so that i can get compete time difference 6:30.
答案1
得分: 4
我建议使用 Duration
。
LocalTime onDutyTime = LocalTime.of(8, 0);
LocalTime offDutyTime = LocalTime.of(14, 30);
Duration d = Duration.between(onDutyTime, offDutyTime);
System.out.println(d);
System.out.println(d.toMinutes());
System.out.println(d.toHours());
System.out.println(d.toMinutesPart());
这将输出:
PT6H30M
390
6
30
英文:
I would recommend using Duration
.
LocalTime onDutyTime = LocalTime.of(8, 0);
LocalTime offDutyTime = LocalTime.of(14, 30);
Duration d = Duration.between(onDutyTime, offDutyTime);
System.out.println(d);
System.out.println(d.toMinutes());
System.out.println(d.toHours());
System.out.println(d.toMinutesPart());
This outputs
PT6H30M
390
6
30
答案2
得分: 3
编辑: 请参考此回答获取更好的方法。
我会使用:
long amount = ChronoUnit.MINUTES.between(start, end);
这将返回两个LocalTime
实例之间的分钟数。
您也可以使用:
long amount = onDutyTime.until(offDutyTime, ChronoUnit.MINUTES);
然后,只需除以60
以获取小时数:
long hours = amount / 60;
并取余数以获取分钟数:
long minutes = amount % 60;
英文:
EDIT: Please refer to this answer for a better approach.
I would use:
long amount = ChronoUnit.MINUTES.between(start, end);
This returns the amount of minutes between two LocalTime
instances.
You could also use:
long amount = onDutyTime.until(offDutyTime, ChronoUnit.MINUTES);
Then, simply divide by 60
to obtain the hours:
long hours = amount / 60;
And get the remainder to obtain the minutes:
long minutes = amount % 60;
答案3
得分: 2
你可以使用以下操作:
LocalTime timeDiff = t2.minusNanos(t1.toNanoOfDay());
结果将包含您所需的所有时间单位,无需将时间量分开。
英文:
You can use the following operation:
LocalTime timeDiff = t2.minusNanos(t1.toNanoOfDay());
The result will contain all time units you want, without need to divide time amounts.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论