在我的Java项目中,我希望将日期时间秒除以5。
I have got - I want
12:00:01 - 12:00:00
12:00:04 - 12:00:05
12:00:06 - 12:00:05
12:00:07 - 12:00:05
12:00:08 - 12:00:10
...
12:00:58 - 12:01:00
日期对象包含日期,例如:Fri May 12 12:00:03 CEST 2017
我想要四舍五入秒来取模 5。我想实现带有四舍五入秒的日期对象。
我如何使用简单的数学或Joda
来做到这一点?
作为 Ole V.V 正确答案的补充:
据我所知(但其他人可能会纠正我(,Joda-Time 提供了舍入功能,但不是 OP 想要的类型,即可配置的步长宽度(此处:5 秒(。所以我怀疑Joda解决方案与基于Java-8的@Ole给出的解决方案非常相似。
我的时间库 Time4J 具有更多的舍入功能,无需考虑舍入数学,如以下代码所示:
import net.time4j.ClockUnit;
import net.time4j.PlainTime;
import net.time4j.format.expert.Iso8601Format;
import java.text.ParseException;
import java.time.LocalTime;
import static net.time4j.PlainTime.*;
public class RoundingOfTime {
public static void main(String... args) throws ParseException {
PlainTime t1 = Iso8601Format.EXTENDED_WALL_TIME.parse("12:59:57");
PlainTime t2 = Iso8601Format.EXTENDED_WALL_TIME.parse("12:59:58");
System.out.println(t1.with(SECOND_OF_MINUTE.roundedHalf(5))); // T12:59:55
System.out.println(t2.with(SECOND_OF_MINUTE.roundedHalf(5))); // T13
LocalTime rounded =
PlainTime.nowInSystemTime()
.with(PRECISION, ClockUnit.SECONDS) // truncating subseconds
.with(SECOND_OF_MINUTE.roundedHalf(5)) // rounding
.toTemporalAccessor(); // conversion to java-time
System.out.println(rounded); // 15:57:05
}
}
方法roundedHalf(int(适用于类PlainTime
中定义的大多数时间元素。我欢迎进一步的增强建议,甚至可能找到一种方法来定义此类方法TemporalAdjuster
。
这里有一个建议:
LocalTime time = LocalTime.now(ZoneId.systemDefault()).truncatedTo(ChronoUnit.SECONDS);
System.out.println("Before rounding: " + time);
int secondsSinceLastWhole5 = time.getSecond() % 5;
if (secondsSinceLastWhole5 >= 3) { // round up
time = time.plusSeconds(5 - secondsSinceLastWhole5);
} else { // round down
time = time.minusSeconds(secondsSinceLastWhole5);
}
System.out.println("After rounding: " + time);
输出示例:
Before rounding: 14:46:33
After rounding: 14:46:35
Before rounding: 14:47:37
After rounding: 14:47:35
% 5
(模 5(运算将为我们提供自时钟上最后一个整整 5 秒以来的秒数,作为区间 0 到 4 中的数字。使用它我们知道要四舍五入的方式。
我正在使用java.time.LocalTime
.对于今天没有明确时区的时间,这是推荐的类。