可以使用before()和after()方法来判断一个时间是否在选择区间内。以下是一个示例代码:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Main {
    public static void main(String[] args) throws ParseException {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        // 选择的开始时间和结束时间
        Date startTime = dateFormat.parse("2021-01-01 00:00:00");
        Date endTime = dateFormat.parse("2021-01-02 00:00:00");

        // 所选的时间
        Date selectedTime = dateFormat.parse("2021-01-01 12:00:00");

        // 判断所选时间是否在选择区间内
        if (selectedTime.after(startTime) && selectedTime.before(endTime)) {
            System.out.println("所选时间在选择区间内");
        } else {
            System.out.println("所选时间不在选择区间内");
        }
    }
}

上述代码中,首先使用SimpleDateFormat类将字符串格式的时间转换为Date类型。然后使用after()方法判断所选时间是否在选择区间的开始时间之后,使用before()方法判断所选时间是否在选择区间的结束时间之前。如果两个条件都满足,则表示所选时间在选择区间内。

Java 判断时间是否在指定区间内 - 使用 before() 和 after() 方法

原文地址: http://www.cveoy.top/t/topic/BcC 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录