Weekend filter for Java 8 LocalDateTime

前端 未结 6 1198
春和景丽
春和景丽 2021-02-20 03:47

I want to write a boolean valued function which returns true if the given LocalDateTime falls between two specific points in time, false otherwise.

Specific

6条回答
  •  甜味超标
    2021-02-20 04:12

    A simple TemporalQuery would do the trick:

    static class IsWeekendQuery implements TemporalQuery{
    
        @Override
        public Boolean queryFrom(TemporalAccessor temporal) {
            return temporal.get(ChronoField.DAY_OF_WEEK) >= 5;
        }
    }
    

    It would be called like this (using .now() to get a value to test):

    boolean isItWeekendNow = LocalDateTime.now().query(new IsWeekendQuery());
    

    Or, specifically in UTC time (using .now() to get a value to test):

    boolean isItWeekendNow = OffsetDateTime.now(ZoneOffset.UTC).query(new IsWeekendQuery());
    

    Going beyond your question, there is no reason to create a new instance of IsWeekendQuery every time it is used, so you might want to create a static final TemporalQuery that encapsulates the logic in a lambda expression:

    static final TemporalQuery IS_WEEKEND_QUERY = 
        t -> t.get(ChronoField.DAY_OF_WEEK) >= 5;
    
    boolean isItWeekendNow = OffsetDateTime.now(ZoneOffset.UTC).query(IS_WEEKEND_QUERY);
    

提交回复
热议问题