0

我正在尝试使用 Java 检查当前日期和时间是否在一周的星期五 17:42 和星期日 17:42 之间。

目前我正在用非常糟糕的代码块来做这件事。这是一个匆忙的解决方案。现在我正在重构,但我在 joda 等中找不到任何方法。

有任何想法吗?谢谢

private final Calendar currentDate = Calendar.getInstance();
private final int day = currentDate.get(Calendar.DAY_OF_WEEK);
private final int hour = currentDate.get(Calendar.HOUR_OF_DAY);
private final int minute = currentDate.get(Calendar.MINUTE);

if (day != 1 && day != 6 && day != 7) {
    if (combined != 0) {
        return badge == 1;
    } else {
        return badge == product;
    }
} else {
    if (day == 6 && hour > 16) {
        if (hour == 17 && minute < 43) {
            if (combined != 0) {
                return badge == 1;
            } else {
                return badge == product;
            }
        } else {
            return badge == 0;
        }
    } else if (day == 6 && hour < 17) {
        if (combined != 0) {
            return badge == 1;
        } else {
            return badge == product;
        }
    } else if (day == 1 && hour > 16) {
        if (hour == 17 && minute < 43) {
            return badge == 0;
        } else {
            if (combined != 0) {
                return badge == 1;
            } else {
                return badge == product;
            }
        }
    } else {
        return badge == 0;
    }
}

我在@MadProgrammer 和@Meno Hochschild 的帮助下使用了这样的解决方案

方法:

public static boolean isBetween(LocalDateTime check, LocalDateTime startTime, LocalDateTime endTime) {
 return ((check.equals(startTime) || check.isAfter(startTime)) && (check.equals(endTime) || check.isBefore(endTime))); }

用法:

static LocalDateTime now = LocalDateTime.now();
static LocalDateTime friday = now.with(DayOfWeek.FRIDAY).toLocalDate().atTime(17, 41);
static LocalDateTime sunday = friday.plusDays(2).plusMinutes(1);

if (!isBetween(now, friday, sunday)) { ... }

再次感谢您的努力。

4

3 回答 3

4

Date并具有可以对/ 、和的Calendar其他实例进行比较的方法DateCalendarequalsbeforeafter

但是,我鼓励使用 Java 8 的新 Time API

public static boolean isBetween(LocalDateTime check, LocalDateTime startTime, LocalDateTime endTime) {
    return ((check.equals(startTime) || check.isAfter(startTime)) && 
                    (check.equals(endTime) || check.isBefore(endTime)));
}

true如果提供LocalDateTime的内容在指定范围内(包括在内),它将返回。

就像是...

LocalDateTime start = LocalDateTime.now();
start = start.withDayOfMonth(26).withHour(17).withMinute(42).withSecond(0).withNano(0);
LocalDateTime end = start.plusDays(2);

LocalDateTime check = LocalDateTime.now();

System.out.println(check + " is within range = " + isBetween(check, start, end));
check = start;
System.out.println(check + " is within range = " + isBetween(check, start, end));
check = end;
System.out.println(check + " is within range = " + isBetween(check, start, end));
check = start.plusDays(1);
System.out.println(check + " is within range = " + isBetween(check, start, end));
check = end.plusMinutes(1);
System.out.println(check + " is within range = " + isBetween(check, start, end));

哪个输出

2015-06-25T18:31:32.969 is within range = false
2015-06-26T17:42 is within range = true
2015-06-28T17:42 is within range = true
2015-06-27T17:42 is within range = true
2015-06-28T17:43 is within range = false

Joda-Time 有一Interval门课,使它更容易

Interval targetInterval = new Interval(targetStart, targetEnd);
System.out.println("Contains interval = " + interval.contains(targetInterval)

这里展示

一种不同的方法...

所以我在回家的路上想,假设你只有想要检查的日期/时间,你如何确定这一天是否在你的范围内

LocalDateTime now = LocalDateTime.now();
boolean isBetween = false;
switch (now.getDayOfWeek()) {
    case FRIDAY:
    case SATURDAY:
    case SUNDAY:
        LocalDateTime lastFriday = getLastFriday(now);
        LocalDateTime nextSunday = getNextSunday(now);
        isBetween = isBetween(now, lastFriday, nextSunday);
        System.out.println(lastFriday + " - " + nextSunday + ": " + end);
        break;
}

它的作用是检查dayOfWeek它是否在所需的范围内,如果是,它会从指定日期查找上一个Friday和下一个,并检查它是否介于它们之间(参见前面的示例)Sunday

lastFridaynextSunday简单地从指定的日期/时间添加/减去 aday直到达到所需的dayOfWeek,然后播种所需的时间限制

public static LocalDateTime getLastFriday(LocalDateTime anchor) {
    LocalDateTime ldt = LocalDateTime.from(anchor);
    return ldt.with(DayOfWeek.FRIDAY).withHour(17).withMinute(42).withSecond(0).withNano(0);
}

public static LocalDateTime getNextSunday(LocalDateTime anchor) {
    LocalDateTime ldt = LocalDateTime.from(anchor);
    return ldt.with(DayOfWeek.SUNDAY).withHour(17).withMinute(42).withSecond(0).withNano(0);
}
于 2015-06-25T08:34:01.643 回答
0

Calendar您可以知道DAY_OF_WEEK给定日期是什么,然后只需检查时间:

Calendar c = Calendar.getInstance();
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);

// in friday the hour must be greater than 17:42
if (dayOfWeek == 5 && ((hour > 17) || (hour == 17 && minute >= 42)) {
    // successss!!
}
// days from 1 to 7... saturday(6) all day
if (dayOfWeek == 6) {
    // successss!!
}
// sunday hour must be lower than 17:42
if (dayOfWeek == 7 && ((hour < 17) || (hour == 17 && minute <= 42)) {
    // successss!!
}
于 2015-06-25T08:24:26.080 回答
0

使用旧 Java的更好解决方案如下所示:

// current timestamp
GregorianCalendar gcal = new GregorianCalendar();

// specify ISO-week (you are searching for friday until sunday in this order)
gcal.setMinimalDaysInFirstWeek(4);
gcal.setFirstDayOfWeek(Calendar.MONDAY);

// sunday at 17:43
GregorianCalendar sunday = (GregorianCalendar) gcal.clone();
sunday.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
sunday.set(Calendar.HOUR_OF_DAY, 17);
sunday.set(Calendar.MINUTE, 43);
sunday.set(Calendar.SECOND, 0);
sunday.set(Calendar.MILLISECOND, 0);

// friday at 17:42
GregorianCalendar friday = (GregorianCalendar) sunday.clone();
friday.add(Calendar.DATE, -2);
friday.add(Calendar.MINUTE, -1);

// logging for test purposes
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
System.out.println(f.format(friday.getTime()));
System.out.println(f.format(gcal.getTime()));
System.out.println(f.format(sunday.getTime()));

// result (assumption: half-open-interval)
boolean withinTimeWindow = !gcal.before(friday) && gcal.before(sunday);

Java-8提供了一种更短的方法(假设 ISO-weekmodel):

LocalDateTime now = LocalDateTime.now();
LocalDateTime friday = now.with(DayOfWeek.FRIDAY).toLocalDate().atTime(17, 42);
LocalDateTime sunday = friday.plusDays(2).plusMinutes(1);
boolean withinTimeWindow = !now.isBefore(friday) && now.isBefore(sunday);

最后,您的等效评估可能如下所示:

  if (!withinTimeWindow) {
        if (combined != 0) {
            return badge == 1;
        } else {
            return badge == product;
        }
  } else {
        return badge == 0;
  }
于 2015-06-25T10:52:24.827 回答