英文:
How to check Time between 2 Dates
问题
我有2个参数(java.util.Date
),我需要检查当前时间是否在这2个日期之间。为此,我需要忽略我的日期,只检查我的时间。
我需要忽略 yyyy/MM/dd
,只检查我的 hh:mm:ss
。例如:
日期1:2008/11/10 08:05:55
日期2:2010/12/11 10:12:33
当前日期:2020:09:29 09:12:13
我需要检查 日期1 <= 当前日期 <= 日期2
但我只需要检查 hh:mm:ss
,如下:
08:05:55 <= 09:12:13 <= 10:12:33 = True
忽略 yyyy/MM/dd
。
英文:
I have 2 params (java.util.Date
) and I need check if my current time is between this 2 dates. For this I need ignore my date and just check my time.
I need ignore yyyy/MM/dd
and just check my hh:mm:ss
. For example:
Date 1: 2008/11/10 08:05:55
Date 2: 2010/12/11 10:12:33
Current Date: 2020:09:29 09:12:13
I need check Date 1 <= Current Date <= Date 2
But I need check just hh:mm:ss
like:
08:05:55 <= 09:12:13 <= 10:12:33 = True
Ignoring the yyyy/MM/dd
答案1
得分: 1
我建议转换为Java 8时间API对象,并使用它们直观的方法。
以下是一些我为您编写的实用方法:
public static boolean nowIsBetweenInclusive(Date start, Date end) {
return timeIsBetweenInclusive(LocalTime.now(), asLocalTime(start), asLocalTime(end));
}
public static LocalTime asLocalTime(@NonNull Date date) {
return date.toInstant().atZone(ZoneId.systemDefault()).toLocalTime();
}
public static boolean timeIsBetweenInclusive(@NotNull LocalTime time, LocalTime start, LocalTime end) {
return start != null && end != null && !time.isBefore(start) && !time.isAfter(end);
}
英文:
I would suggest converting to Java 8 time API objects and using their intuitive methods.
Here's some utility methods I've put together for you use:
public static boolean nowIsBetweenInclusive(Date start, Date end) {
return timeIsBetweenInclusive(LocalTime.now(), asLocalTime(start), asLocalTime(end));
}
public static LocalTime asLocalTime(@NonNull Date date) {
return date.toInstant().atZone(ZoneId.systemDefault()).toLocalTime();
}
public static boolean timeIsBetweenInclusive(@NotNull LocalTime time, LocalTime start, LocalTime end) {
return start != null && end != null && !time.isBefore(start) && !time.isAfter(end);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论