This example is a custom TemporalQuery that will determine if a date is a weekend date. A weekend date is to be considered Saturday or Sunday day of week. Implementing the TemporalQuery interface with the queryFrom(TemporalAccessor) method allows for a way to extract information from a temporal object. The queryFrom method compares the passed-in date against the DayOfWeek and returns TRUE if the day of the week is SATURDAY or SUNDAY else returning false.
Setup public class WeekendQuery implements TemporalQuery < Boolean > {
/* (non-Javadoc)
* @see java.time.temporal.TemporalQuery#queryFrom(java.time.temporal.TemporalAccessor)
*/
@Override
public Boolean queryFrom ( TemporalAccessor date ) {
int dayOfWeekNumber = date . get ( ChronoField . DAY_OF_WEEK );
DayOfWeek dayOfWeek = DayOfWeek . of ( dayOfWeekNumber );
if ( dayOfWeek == DayOfWeek . SATURDAY || dayOfWeek == DayOfWeek . SUNDAY ) {
return Boolean . TRUE ;
} else {
return Boolean . FALSE ;
}
}
}
Weekend query @Test
public void check_if_date_is_weekend () {
LocalDate date = LocalDate . of ( 2014 , 02 , 02 ); // Sunday
Boolean workDay = date . query ( new WeekendQuery ());
assertTrue ( workDay );
}
Use query with lambda @Test
public void filter_dates_by_weekend () {
List < LocalDate > randomDays = Lists . newArrayList (
LocalDate . of ( 2014 , Month . FEBRUARY , 16 ), // Sunday
LocalDate . of ( 2014 , Month . APRIL , 19 ), // Saturday
LocalDate . of ( 2014 , Month . MAY , 30 ), // Friday
LocalDate . of ( 2014 , Month . DECEMBER , 12 ), // Friday
LocalDate . of ( 2014 , Month . DECEMBER , 17 ) // Wednesday
);
// filter weekend days
List < LocalDate > weekendDays = randomDays
. stream ()
. filter ( p -> p . query ( new WeekendQuery ()))
. collect ( Collectors . toList ());
assertEquals ( 2 , weekendDays . size ());
}
Weekend query posted by Justin Musgrove on 07 February 2014
Tagged: java, java-date, and java-date-query
Share on: Facebook Google+
All the code on this page is available on github:
WeekendQuery.java