Java judges whether the time is between two time ranges, outside
import java.time.LocalTime;
public class TestExample {
public static void main(String[] args) {
// 获取当前时间
LocalTime now = LocalTime.now();
// 设置前一天的结束时间为第二天的8点
LocalTime previousDayEndTime = LocalTime.of(8, 0);
// 设置第二天的开始时间为19点40分
LocalTime nextDayStartTime = LocalTime.of(19, 40);
// 判断当前时间是否在前一天的结束时间到第二天的开始时间之间
if (now.isAfter(previousDayEndTime) && now.isBefore(nextDayStartTime)) {
System.out.println("当前时间在前一天的结束时间到第二天的开始时间之间");
} else {
System.out.println("当前时间不在前一天的结束时间到第二天的开始时间之间");
}
System.out.println(now);
}
}
This code will determine whether the current time is between the end time of the previous day (8:00 of the next day) and the start time of the next day (19:40). If it is within this time range, output "do not send SMS"; otherwise output "send SMS". Please modify the logic part of sending SMS in the code according to your actual needs.
What does isAfter mean?
isAfter
LocalTime
Is a method of the class in Java , which is used to compare whether two times are in order, where the time object calling this method should be after the time specified by the method parameter.
Specifically, isAfter
the method returns a boolean
value, if the time object on which the method is called is later than the time specified by the method parameter, otherwise it true
returns false
.
In the code example above:
now.isAfter(previousDayEndTime)
This statement is used to judge now
whether the current time is later than the end time of the previous day previousDayEndTime
, if yes, it means that the current time is after the end time of the previous day.
Similarly, isBefore
the method can be used to compare whether two times are in order, where the time object calling this method should be before the time specified by the method parameter.
Note that the comparison here is based on the order of time rather than date.
What does isBefore mean?
isBefore
LocalTime
Is a method of class in Java , which is used to compare whether two times are in order, and the time object calling this method should be before the time specified by the method parameter.
Specifically, isBefore
the method returns a boolean
value, if the time object on which the method is called is earlier than the time specified by the method parameter, otherwise it true
returns false
.
In the code example above:
now.isBefore(nextDayStartTime)
This statement is used to judge now
whether the current time is earlier than the start time of the next day nextDayStartTime
, if yes, it means that the current time is before the start time of the next day.
Similarly, isAfter
methods are used to determine whether one time is later than another, and isBefore
methods are used to determine whether one time is earlier than another.
Note that the comparison here is based on the order of time rather than date.