java中判断是否在夜间

在夜间模式时间段可以自定义的情况下,判断传入的时间在不在夜间模式时间段内。
使用JodaTime进行时间操作。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
private boolean isInNight(long timeInMillis) {
DateTime from = new LocalTime("22:00").toDateTimeToday();
DateTime to = new LocalTime("11:00").toDateTimeToday();
DateTime nextDayOfNightModeTo = to;
if (to.compareTo(from) < 0) { // to < from
nextDayOfNightModeTo = to.plusDays(1);
}
long millisOfNightMode = Seconds.secondsBetween(from, nextDayOfNightModeTo).getSeconds() * 1000L;
DateTime dateTime = new DateTime(timeInMillis);
if (dateTime.compareTo(from) > 0) {
long millisBetween = dateTime.getMillis() - from.getMillis();
if (millisOfNightMode > millisBetween) {
return true;
}
} else if (dateTime.compareTo(to) < 0) {
long millisBetween = to.getMillis() - from.getMillis();
if (millisOfNightMode > millisBetween) {
return true;
}
}
return false;
}