周末过滤器用于Java 8 LocalDateTime

问题描述 投票:10回答:5

我想编写一个布尔值函数,如果给定的LocalDateTime落在两个特定时间点之间,则返回true,否则返回false。

具体来说,如果给定日期在格林威治标准时间周五22:00到格林威治标准时间周日23:00之间,我希望有一个LocalDateTime过滤器。

骨架看起来像这样:

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

这基本上是一个周末过滤器,我想知道是否有一个简单的解决方案与新的Java 8时间库(或任何其他现有的过滤器方法)。

我知道如何检查星期几,小时等,但要避免重新发明轮子。

java filter java-8 java-time
5个回答
1
投票

我写了一个小程序来实现这个目标

程序

public class TestWeekend {
    private static final int FRIDAY = 5;
    private static final int SATURDAY = 6;
    private static final int SUNDAY = 7;
    private static final Integer WEEKEND_START_FRIDAY_CUT_OFF_HOUR = 22;
    private static final Integer WEEKEND_END_SUNDAY_CUT_OFF_HOUR = 23;
    private static List<Integer> weekendDaysList = Arrays.asList(FRIDAY, SATURDAY, SUNDAY);

    public static void main(String []args) throws FileNotFoundException {
        System.out.println(" is weekend - "+isWeekend(LocalDateTime.of(2016,4,22,18,39)));
        System.out.println(" is weekend - "+isWeekend(LocalDateTime.of(2016,4,22,21,59)));
        System.out.println(" is weekend - "+isWeekend(LocalDateTime.of(2016,4,22,22,0)));
        System.out.println(" is weekend - "+isWeekend(LocalDateTime.of(2016,4,23,5,0)));
        System.out.println(" is weekend - "+isWeekend(LocalDateTime.of(2016,4,24,8,0)));
        System.out.println(" is weekend - "+isWeekend(LocalDateTime.of(2016,4,24,22,59)));
        System.out.println(" is weekend - "+isWeekend(LocalDateTime.of(2016,4,24,23,0)));
        System.out.println(" is weekend - "+isWeekend(LocalDateTime.of(2016,4,25,11,5)));
    }

    public static  boolean isWeekend(LocalDateTime dateTime) {
        System.out.print("Date - "+dateTime+" , ");
        if(weekendDaysList.contains(dateTime.getDayOfWeek().getValue()) ){
            if(SATURDAY ==  dateTime.getDayOfWeek().getValue()){
                return true;
            }
            if(FRIDAY == dateTime.getDayOfWeek().getValue() && dateTime.getHour() >=WEEKEND_START_FRIDAY_CUT_OFF_HOUR){
               return true;
            }else if(SUNDAY == dateTime.getDayOfWeek().getValue() && dateTime.getHour()  < WEEKEND_END_SUNDAY_CUT_OFF_HOUR ){
                return   true;
            }
        }
        //Checks if dateTime falls in between Friday's 22:00 GMT and Sunday's 23:00 GMT
         return false;
    }

 }

7
投票

您如何期待这样的图书馆工作?当你的周末开始和结束时,你仍然需要告诉它,它最终会比简单的更短

boolean isWeekend(LocalDateTime dt) {
    switch(dt.getDayOfWeek()) {
        case FRIDAY:
            return dt.getHour() >= ...;
        case SATURDAY:
            return true;
        case SUNDAY:
            return dt.getHour() < ...;
        default:
            return false;
    }
}

4
投票

一个简单的TemporalQuery可以做到这一点:

static class IsWeekendQuery implements TemporalQuery<Boolean>{

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

它会像这样调用(使用.now()来获取值来测试):

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

或者,特别是在UTC时间(使用.now()获取要测试的值):

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

超越你的问题,没有理由每次使用它时创建一个新的IsWeekendQuery实例,所以你可能想要创建一个静态的最终TemporalQuery,它将逻辑封装在lambda表达式中:

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);

3
投票

Temporal Query

java.time框架包含一个用于询问日期时间值的体系结构:Temporal QueryTemporalQuery接口的一些实现可以在复数命名的TemporalQueries类中找到。

您也可以编写自己的实现。 TemporalQuery是一个functional interface,意思是它有一个声明的方法。该方法是queryFrom

这是我第一次尝试实施TemporalQuery,所以请耐心等待。这是完整的课程。免费使用(ISC License),但完全由您自己承担风险。

棘手的部分是问题的要求是周末由UTC定义,而不是传递的日期时间值的时区或偏移量。所以我们需要将传递的日期时间值调整为UTC。虽然Instant在逻辑上是等价的,但我使用OffsetDateTimeoffset of UTC,因为它更灵活。特别是OffsetDateTime提供了getDayOfWeek方法。

CAVEAT:我不知道我是否正在用正统方法做事,因为我没有完全理解java.time设计的基础,正如其创作者所预期的那样。具体来说,我不确定我的TemporalAccessor ta铸造到java.time.chrono.ChronoZonedDateTime是否合适。但它似乎运作良好。

如果这个类与Instant实例以及ChronoZonedDateTime / ZonedDateTime一起使用会更好。

package com.example.javatimestuff;

import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;

/**
 * Answers whether a given temporal value is between Friday 22:00 UTC
 * (inclusive) and Sunday 23:00 UTC (exclusive).
 *
 * @author Basil Bourque. 
 * 
 * © 2016 Basil Bourque
 * This source code may be used according to the terms of the ISC License (ISC). (Basically, do anything but sue me.)
 * https://opensource.org/licenses/ISC
 *
 */
public class WeekendFri2200ToSun2300UtcQuery implements TemporalQuery<Boolean> {

    static private final EnumSet<DayOfWeek> WEEKEND_DAYS = EnumSet.of ( DayOfWeek.FRIDAY , DayOfWeek.SATURDAY , DayOfWeek.SUNDAY );
    static private final OffsetTime START_OFFSET_TIME = OffsetTime.of ( LocalTime.of ( 22 , 0 ) , ZoneOffset.UTC );
    static private final OffsetTime STOP_OFFSET_TIME = OffsetTime.of ( LocalTime.of ( 23 , 0 ) , ZoneOffset.UTC );

    @Override
    public Boolean queryFrom ( TemporalAccessor ta ) {
        if (  ! ( ta instanceof java.time.chrono.ChronoZonedDateTime ) ) {
            throw new IllegalArgumentException ( "Expected a java.time.chrono.ChronoZonedDateTime such as `ZonedDateTime`. Message # b4a9d0f1-7dea-4125-b68a-509b32bf8d2d." );
        }

        java.time.chrono.ChronoZonedDateTime czdt = ( java.time.chrono.ChronoZonedDateTime ) ta;

        Instant instant = czdt.toInstant ();
        OffsetDateTime odt = OffsetDateTime.ofInstant ( instant , ZoneOffset.UTC );
        DayOfWeek dayOfWeek = odt.getDayOfWeek ();
        if (  ! WeekendFri2200ToSun2300UtcQuery.WEEKEND_DAYS.contains ( dayOfWeek ) ) {
            // If day is not one of our weekend days (Fri-Sat-Sun), then we know this moment is not within our weekend definition.
            return Boolean.FALSE;
        }
        // This moment may or may not be within our weekend. Very early Friday or very late Sunday is not a hit.
        OffsetDateTime weekendStart = odt.with ( DayOfWeek.FRIDAY ).toLocalDate ().atTime ( START_OFFSET_TIME );  // TODO: Soft-code with first element of WEEKEND_DAYS.
        OffsetDateTime weekendStop = odt.with ( DayOfWeek.SUNDAY ).toLocalDate ().atTime ( STOP_OFFSET_TIME );  // TODO: Soft-code with last element of WEEKEND_DAYS.

        // Half-Open -> Is equal to or is after the beginning, AND is before the ending.
        // Not Before -> Is equal to or is after the beginning.
        Boolean isWithinWeekend = (  ! odt.isBefore ( weekendStart ) ) && ( odt.isBefore ( weekendStop ) );

        return isWithinWeekend;
    }

    static public String description () {
        return "WeekendFri2200ToSun2300UtcQuery{ " + START_OFFSET_TIME + " | " + WEEKEND_DAYS + " | " + STOP_OFFSET_TIME + " }";
    }

}

让我们用那个TemporalQuery。虽然定义TemporalQuery需要一些工作,但使用它是非常简单和容易的:

  1. 实例化TemporalQuery对象。
  2. 应用于我们的日期时间对象。 (在我们的案例中任何java.time.chrono.ChronoZonedDateTime的例子,例如ZonedDateTime

正在使用。

WeekendFri2200ToSun2300UtcQuery query = new WeekendFri2200ToSun2300UtcQuery ();

我添加了一个静态description方法用于调试和记录,以验证查询的设置。这是我自己发明的方法,TemporalQuery界面不需要。

System.out.println ( "Weekend is: " + WeekendFri2200ToSun2300UtcQuery.description () );

今天是星期二。不应该在周末。

ZonedDateTime now = ZonedDateTime.now ( ZoneId.of ( "America/Montreal" ) );
Boolean nowIsWithinWeekend = now.query ( query );
System.out.println ( "now: " + now + " is in weekend: " + nowIsWithinWeekend );

现在这周五早上。不应该在周末。

ZonedDateTime friday1000 = ZonedDateTime.of ( LocalDate.of ( 2016 , 4 , 29 ) , LocalTime.of ( 10 , 0 ) , ZoneId.of ( "America/Montreal" ) );
Boolean friday1000IsWithinWeekend = friday1000.query ( query );
System.out.println ( "friday1000: " + friday1000 + " is in weekend: " + friday1000IsWithinWeekend );

本周五晚些时候。在周末应该是真的。

ZonedDateTime friday2330 = ZonedDateTime.of ( LocalDate.of ( 2016 , 4 , 29 ) , LocalTime.of ( 23 , 30 ) , ZoneId.of ( "America/Montreal" ) );
Boolean friday2330IsWithinWeekend = friday2330.query ( query );
System.out.println ( "friday2330: " + friday2330 + " is in weekend: " + friday2330IsWithinWeekend );

跑步时

周末是:WeekendFri2200ToSun2300UtcQuery {22:00Z | [星期五,星期六,星期日] | 23:00Z}

现在:2016-04-26T20:35:01.014-04:00 [美国/蒙特利尔]周末:假

星期五1000:2016-04-29T10:00-04:00 [美国/蒙特利尔]周末:假

星期五2330:2016-04-29T23:30-04:00 [美国/蒙特利尔]周末:真的

Local… does not mean local

参考问题...说你想比较一个LocalDateTime与UTC中的值(周末开始/停止)是没有意义的。 LocalDateTime没有偏离UTC的时区。虽然命名可能是违反直觉的,但Local…类意味着它们可以适用于任何没有特定地点的地方。所以它们没有任何意义,它们不是时间轴上的一个点,直到您应用指定偏移或时区。

整个答案假设您对此术语感到困惑,并且打算比较时间轴上的实际时刻。


1
投票

希望这可以帮助:

LocalDateTime localDateTime = LocalDateTime.now(DateTimeZone.UTC);
int dayNum = localDateTime.get(DateTimeFieldType.dayOfWeek());
boolean isWeekend = (dayNum == DateTimeConstants.SATURDAY || dayNum == DateTimeConstants.SUNDAY);

这是在不使用许多私有常量的情况下执行此操作的最简单方法。

© www.soinside.com 2019 - 2024. All rights reserved.