如何检查两个日期之间的时间。

huangapple go评论75阅读模式
英文:

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 &lt;= Current Date &lt;= Date 2

But I need check just hh:mm:ss like:

08:05:55 &lt;= 09:12:13 &lt;= 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 &amp;&amp; end != null &amp;&amp; !time.isBefore(start) &amp;&amp; !time.isAfter(end);
}

huangapple
  • 本文由 发表于 2020年9月29日 21:46:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/64120965.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定