如果前后仅5分钟,如何舍入到最接近的小时? [英] How to round off to the closest hour if its only 5 minutes ahead or behind?
问题描述
我想在Java中将 Instant
舍入到最接近的小时,但前提是它在最接近的小时的5分钟之内.
I want to round off an Instant
to its closest hour in Java, but only if it's within 5 minutes of the closest hour.
假设时间是:2021-02-08T19:02:49.594
预期结果:2021-02-08T19:00:00.000
Suppose the time is: 2021-02-08T19:02:49.594
Expected result: 2021-02-08T19:00:00.000
同样,如果时间是:2021-02-08T19:56:49.594
预期结果:2021-02-08T20:00:00.000
Similarly, if the time is: 2021-02-08T19:56:49.594
Expected result: 2021-02-08T20:00:00.000
但是如果时间是2021-02-08T19:54:49.594或2021-02-08T19:06:49.594,那么什么也不做.
But if the time is 2021-02-08T19:54:49.594 or 2021-02-08T19:06:49.594 then do nothing.
推荐答案
您可以简单地检查日期时间的分钟部分,然后根据需要将其截断为小时.
You can simply check the minute part of the date-time and truncate it to hours as per the requirement.
演示:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
class Main {
public static void main(String[] args) {
// Test
String[] arr = { "2021-02-08T19:02:49.594", "2021-02-08T19:56:49.594", "2021-02-08T19:54:49.594",
"2021-02-08T19:06:49.594" };
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSS");
for (String s : arr) {
System.out.println(roundToNearestHour(s).format(dtf));
}
}
static LocalDateTime roundToNearestHour(String str) {
LocalDateTime ldt = LocalDateTime.parse(str);
int minute = ldt.getMinute();
return minute < 5 ? ldt.truncatedTo(ChronoUnit.HOURS)
: (minute >= 55 ? ldt.plusHours(1).truncatedTo(ChronoUnit.HOURS) : ldt);
}
}
输出:
2021-02-08T19:00:00.000
2021-02-08T20:00:00.000
2021-02-08T19:54:49.594
2021-02-08T19:06:49.594
这篇关于如果前后仅5分钟,如何舍入到最接近的小时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!