Java判断一个时间是否在某个时间区间内

/**
     * 判断当前时间是否在[startTime, endTime]区间,注意时间格式要一致
     * 
     * @param nowTime 当前时间
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return
     */
    public static boolean isEffectiveDate(Date nowTime, Date startTime, Date endTime) {
        if (nowTime.getTime() == startTime.getTime()
                || nowTime.getTime() == endTime.getTime()) {
            return true;
        }

        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);

        Calendar begin = Calendar.getInstance();
        begin.setTime(startTime);

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);

        if (date.after(begin) && date.before(end)) {
            return true;
        } else {
            return false;
        }
    }

测试:

public static void main(String[] args) throws ParseException {
		String dates = DateUtils.getDate("yyyy-MM-dd HH:mm");// 当前时间
		String strDateBegin = "2021-02-22 23:59";
		String strDateEnd = "2021-06-02 23:59";
		String format = "yyyy-MM-dd HH:mm";
        Date nowTime = new SimpleDateFormat(format).parse(dates);
        Date startTime = new SimpleDateFormat(format).parse(strDateBegin);
        Date endTime = new SimpleDateFormat(format).parse(strDateEnd);
        System.out.println(isEffectiveDate(nowTime, startTime, endTime));
	}

你可能感兴趣的:(Java)