Java 8 LocalDateTime轮到下一个X分钟 [英] Java 8 LocalDateTime round to next X minutes

查看:695
本文介绍了Java 8 LocalDateTime轮到下一个X分钟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将Java 8 LocalDateTime转换为最接近的5分钟。例如。

I want to convert Java 8 LocalDateTime to nearest 5 minutes. E.g.

1601  ->  1605
1602  ->  1605
1603  ->  1605
1604  ->  1605
1605  ->  1605
1606  ->  1610
1607  ->  1610
1608  ->  1610
1609  ->  1610
1610  ->  1610

我想使用LocalDateTime或Math api的现有功能。有什么建议吗?

I would like to use existing functionality of LocalDateTime or Math api. Any suggestions?

推荐答案

您可以使用以下方式向下一个五分钟的时间轮转:

You can round towards the next multiple of five minutes using:

LocalDateTime dt = …
dt = dt.withSecond(0).withNano(0).plusMinutes((65-dt.getMinute())%5);

您可以使用

LocalDateTime dt=LocalDateTime.now().withHour(16).withSecond(0).withNano(0);
for(int i=1; i<=10; i++) {
    dt=dt.withMinute(i);
    System.out.printf("%02d%02d -> ", dt.getHour(), dt.getMinute());
    // the rounding step:
    dt=dt.plusMinutes((65-dt.getMinute())%5);
    System.out.printf("%02d%02d%n", dt.getHour(), dt.getMinute());
}

1601 -> 1605
1602 -> 1605
1603 -> 1605
1604 -> 1605
1605 -> 1605
1606 -> 1610
1607 -> 1610
1608 -> 1610
1609 -> 1610
1610 -> 1610

(在这个例子中,我只清除秒和纳米一次,因为它们保持为零)。

(in this example, I clear the seconds and nanos only once as they stay zero).

这篇关于Java 8 LocalDateTime轮到下一个X分钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆