Java 判断 Date 类型时间是否在时间区间内 (包含开始和结束时间)
可以使用'before()'和'after()'方法来判断一个'Date'类型的时间是否在一个时间区间内。
假设有一个'Date'类型的变量'currentTime'表示当前时间,还有两个'Date'类型的变量'startTime'和'endTime'表示时间区间的开始和结束时间。
以下是使用'before()'和'after()'方法进行判断的示例代码:
import java.util.Date;
public class Main {
public static void main(String[] args) {
Date currentTime = new Date();
Date startTime = // 设置开始时间
Date endTime = // 设置结束时间
if (currentTime.before(startTime)) {
System.out.println('当前时间在时间区间之前');
} else if (currentTime.after(endTime)) {
System.out.println('当前时间在时间区间之后');
} else {
System.out.println('当前时间在时间区间之内');
}
}
}
在上述示例代码中,使用'before()'方法判断'currentTime'是否在'startTime'之前,使用'after()'方法判断'currentTime'是否在'endTime'之后。根据判断结果输出相应的提示信息。
需要注意的是,'before()'方法返回'true'表示当前时间在指定时间之前(早于指定时间),'after()'方法返回'true'表示当前时间在指定时间之后(晚于指定时间)。同时,如果两个时间相等,'before()'和'after()'方法都会返回'false'。
原文地址: https://www.cveoy.top/t/topic/zVn 著作权归作者所有。请勿转载和采集!