Java: how do I check if a Date is within a certain range?

后端 未结 12 682
耶瑟儿~
耶瑟儿~ 2020-11-22 16:39

I have a series of ranges with start dates and end dates. I want to check to see if a date is within that range.

Date.before() and Date.after() seem to be a little a

12条回答
  •  我在风中等你
    2020-11-22 16:53

    Since Java 8

    NOTE: All, but one, Date's constructors are deprecated. Most of the Date's methods are deprecated. REF: Date: Deprecated Methods. All, but Date::from(Instant), static methods are deprecated.

    So, since java 8 consider using Instant (immutable, thread-safe, leap-seconds aware) type rather than Date. REF: Instant

      static final LocalTime MARKETS_OPEN = LocalTime.of(07, 00);
      static final LocalTime MARKETS_CLOSE = LocalTime.of(20, 00);
    
        // Instant utcTime = testDate.toInstant();
        var bigAppleTime = ZonedDateTime.ofInstant(utcTime, ZoneId.of("America/New_York"));
    

    within the range INCLUSIVE:

        return !bigAppleTime.toLocalTime().isBefore(MARKETS_OPEN)
            && !bigAppleTime.toLocalTime().isAfter(MARKETS_CLOSE);
    

    within the range EXCLUSIVE:

        return bigAppleTime.toLocalTime().isAfter(MARKETS_OPEN)
            && bigAppleTime.toLocalTime().isBefore(MARKETS_CLOSE);
    

提交回复
热议问题