Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weekend filter for Java 8 LocalDateTime

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

Specifically I want to have a LocalDateTime filter if a given date is between 22:00 GMT Friday and 23:00 GMT Sunday.

A skeleton could look like this:

public boolean isWeekend(LocalDateTime dateTime) {
    //Checks if dateTime falls in between Friday's 22:00 GMT and Sunday's 23:00 GMT
    //return ...???
}

This is basically a weekend filter and I'm wondering if there is a simple solution with the new Java 8 Time library(or any other existing filter methods).

I know how check for day of week, hour etc. but avoid to reinvent the wheel.

like image 808
Juergen Avatar asked Apr 26 '16 06:04

Juergen


2 Answers

How would you expect such a library to work? You would still need to tell it when your weekend begins and ends and it would end up being not much shorter than the simple

boolean isWeekend(LocalDateTime dt) {
    switch(dt.getDayOfWeek()) {
        case FRIDAY:
            return dt.getHour() >= ...;
        case SATURDAY:
            return true;
        case SUNDAY:
            return dt.getHour() < ...;
        default:
            return false;
    }
}
like image 170
Misha Avatar answered Sep 22 '22 10:09

Misha


A simple TemporalQuery would do the trick:

static class IsWeekendQuery implements TemporalQuery<Boolean>{

    @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<Boolean> IS_WEEKEND_QUERY = 
    t -> t.get(ChronoField.DAY_OF_WEEK) >= 5;

boolean isItWeekendNow = OffsetDateTime.now(ZoneOffset.UTC).query(IS_WEEKEND_QUERY);
like image 23
Hank D Avatar answered Sep 21 '22 10:09

Hank D