java如何判断一个时间是否在一个时间段内
可以使用Java中的Date和Calendar类来判断一个时间是否在一个时间段内。
- 使用Date类
import java.util.Date;
public class TimeInInterval {
public static void main(String[] args) {
Date start = new Date(2021, 8, 1, 10, 0, 0); // 时间段开始时间
Date end = new Date(2021, 8, 1, 11, 0, 0); // 时间段结束时间
Date time = new Date(2021, 8, 1, 10, 30, 0); // 需要判断的时间
if (time.after(start) && time.before(end)) {
System.out.println("时间在时间段内");
} else {
System.out.println("时间不在时间段内");
}
}
}
- 使用Calendar类
import java.util.Calendar;
public class TimeInInterval {
public static void main(String[] args) {
Calendar start = Calendar.getInstance();
start.set(2021, 8, 1, 10, 0, 0); // 时间段开始时间
Calendar end = Calendar.getInstance();
end.set(2021, 8, 1, 11, 0, 0); // 时间段结束时间
Calendar time = Calendar.getInstance();
time.set(2021, 8, 1, 10, 30, 0); // 需要判断的时间
if (time.after(start) && time.before(end)) {
System.out.println("时间在时间段内");
} else {
System.out.println("时间不在时间段内");
}
}
}
以上两种方法都可以判断一个时间是否在一个时间段内。注意,Date类在Java 8中已经被标记为过时,建议使用Java 8中引入的新的日期和时间API
原文地址: https://www.cveoy.top/t/topic/g8Bv 著作权归作者所有。请勿转载和采集!