ACz*_*ACz 0 java date rounding jodatime
在我的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
Run Code Online (Sandbox Code Playgroud)
日期对象包含日期,例如:Fri May 12 12:00:03 CEST 2017
我想要圆形秒数来模数5.我想要使用舍入秒来实现Date对象.
我怎么能用简单的数学运算Joda呢?
正如Ole VV正确答案的补充:
据我所知(但其他人可能会纠正我),Joda-Time提供了舍入功能,但不是OP想要的类型,即可配置的步长(这里:5秒).因此我怀疑Joda解决方案与@Ole基于Java-8的解决方案非常相似.
我的时间库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
}
}
Run Code Online (Sandbox Code Playgroud)
方法roundedHalf(int)适用于类中定义的大多数时间元素PlainTime.我欢迎进一步的改进建议,甚至可能找到一种方法来定义这样的方法TemporalAdjuster.
| 归档时间: |
|
| 查看次数: |
326 次 |
| 最近记录: |