使用 Joda 或标准 Java API 检查日期是否在时间范围内

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2902780/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 23:21:29  来源:igfitidea点击:

Check if date is within time range using Joda or standard Java API

javadatetimejodatimedate-range

提问by EugeneP

I have first time as string '12:00:00' and another '19:00:00'. How to check time portion of the day is within these time values?

我第一次作为字符串 '12:00:00' 和另一个 '19:00:00' 。如何检查一天中的时间部分是否在这些时间值内?

回答by Mark McLaren

Using Joda Time you could do something like this:

使用 Joda Time 你可以做这样的事情:

DateTime start = new DateTime(2010, 5, 25, 12, 0, 0, 0);
DateTime end = new DateTime(2010, 5, 25, 21, 0, 0, 0);
Interval interval = new Interval(start, end);
DateTime test = new DateTime(2010, 5, 25, 16, 0, 0, 0);
System.out.println(interval.contains(test));

回答by Andreas Dolk

Create calendar instances of the start and end times for the same day as your 'test' date. Then you can easily compare the calendar objects to determine if the current date is inside or outside the range.

为“测试”日期的同一天创建开始时间和结束时间的日历实例。然后您可以轻松地比较日历对象以确定当前日期是在范围内还是在范围外。