舍入时间(秒) [英] Round time by seconds
问题描述
在我的Java项目中,我想将日期时间秒数除以5。
In my Java project I want round Date time seconds which is divided by 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
日期对象包含日期,例如: 2017年5月12日星期五12:00:03 CEST
,我想将秒数取模5。我想用舍入秒数实现Date对象。
Date object contain date for example: Fri May 12 12:00:03 CEST 2017
and I want round seconds to modulo 5. I want achieve Date object with rounded seconds.
如何使用简单的数学方法做到这一点或 Joda
?
How can I do this using simple math or Joda
?
推荐答案
以下是一个建议:
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之间的一个数字。这样我们就知道舍入的方式。
The % 5
(modulo 5) operation will give us the number of seconds since the last whole 5 seconds on the clock, as a number in the interval 0 through 4. Using that we know which way to round.
我正在使用 java.time.LocalTime
。这是今天没有明确时区的推荐班级。
I am using java.time.LocalTime
. It’s the recommended class for times without an explicit time zone today.
这篇关于舍入时间(秒)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!