我想编写一个布尔值函数,如果给定的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时间库(或任何其他现有的过滤方法)。
我知道如何检查星期几,小时等,但要避免重新发明轮子。
答案 0 :(得分: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;
}
}
答案 1 :(得分: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
的新实例,因此你可能想要创建一个静态final 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);
答案 2 :(得分:3)
java.time框架包含一个用于询问日期时间值的架构:Temporal Query。 TemporalQuery
接口的某些实现可以在复数命名的TemporalQueries
类中找到。
您也可以编写自己的实现。 TemporalQuery
是functional interface,意味着它声明了一个方法。方法是queryFrom
。
这是我在实施TemporalQuery
时的第一次尝试,所以请耐心等待。这是完整的课程。免费使用(ISC License),但完全由您自己承担风险。
棘手的部分是问题的要求是周末由UTC定义,而不是传递的日期时间值的时区或偏移量。所以我们需要将传递的日期时间值调整为UTC。虽然Instant
在逻辑上是等效的,但我使用OffsetDateTime
和offset 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
需要一些工作,但使用它是非常简单和容易的:
TemporalQuery
对象。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 [美国/蒙特利尔]周末:假
friday1000:2016-04-29T10:00-04:00 [美国/蒙特利尔]周末:假
friday2330:2016-04-29T23:30-04:00 [美国/蒙特利尔]周末:真的
Local…
并不代表本地参考问题...说你要比较LocalDateTime
与UTC中的值(周末开始/停止)是没有意义的。 LocalDateTime
没有偏离UTC的时区。虽然命名可能违反直觉,但Local…
类意味着它们可以应用于任何没有特定地点的地方。所以它们没有任何意义,它们不是时间轴上的一个点,直到您应用指定偏移或时区。
整个答案假设您对此术语感到困惑,并且打算比较时间轴上的实际时刻。
答案 3 :(得分:1)
我写了一个小程序来实现这个目标
<强> PROGRAM 强>
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;
}
}
答案 4 :(得分:1)
希望这会有所帮助:
LocalDateTime localDateTime = LocalDateTime.now(DateTimeZone.UTC);
int dayNum = localDateTime.get(DateTimeFieldType.dayOfWeek());
boolean isWeekend = (dayNum == DateTimeConstants.SATURDAY || dayNum == DateTimeConstants.SUNDAY);
这是在不使用许多私有常量的情况下执行此操作的最简单方法。
答案 5 :(得分:0)
另一种Java 8+解决方案是使用Predicate
测试日期是否在周末。
Predicate<LocalDate> isWeekend = date -> DayOfWeek.from(date).get(ChronoField.DAY_OF_WEEK) > 5;
然后,您可以将其应用到像这样的流中
someListOfDates.stream()
.filter(isWeekend)
.forEach(System.out::println);
不需要外部依赖项。 (不过,请在生产中使用记录器。)