获取Java中满足条件的下一个日期
我知道这应该很简单,但我在互联网上找不到任何东西。
鉴于某些条件,我想Date在满足条件时获得下一个。例如,如果条件是minute = 01并且second = 30现在时间是15:58:00,则函数应该在今天返回16:01:30。我如何在 Java 中完成此操作?
我需要能够设置至少秒、分钟和小时的条件,但我希望有可能将一个条件设置为任何值(如上面的示例,未指定小时)。
感谢并抱歉我的英语不好。
编辑:
我看到有些事情可能需要澄清:我想总是在满足条件的当前时间之后获得一个日期(或其他)。此外,这适用于 Minecraft Spigot 服务器,也许此信息可以提供帮助。
回答
您可以为此使用流:
Optional<LocalDateTime> firstMatch =
Stream.iterate(
LocalDateTime.now(),
ldt -> ldt.plusSeconds(1L))
.filter(
// Insert your condition here
ldt -> ldt.getSecond() == 0)
.findFirst();
这段代码所做的是获取电流LocalDateTime并使用它来生成LocalDateTime对象流(每次将时间提前 1 秒)。一旦遇到LocalDateTime与提供的条件匹配的 ,它就会返回此对象并终止流。
请记住,如果条件需要一段时间才能变为真,则使用这种方法会生成很多对象,因此效率不高。
如果你想剥离纳秒替换LocalDateTime.now()为LocalDateTime.now().withNano(0).
- Imho it is more beautiful than a while-loop, but that's only a personal opinion. To explain the code a bit: Jeroen creates an endless Stream of objects. He starts with a date object for now and creates a new object which is 1 second in the future. The stream takes care of the rest and so you get LocalDateTime objects for every second from now on. In the filter you define the condition to filter the stream, but you get every timestamp that meet this, so you have to use findfirst. Then you get the first object that meets your conditions. As mentioned you generate a lot of objects ...