给定字符串格式的日期,例如:2021-11-11 08:12:25
给定范围,例如 : 6:00-22:00
结果输出为:true
public class Test {
/**
* 判断日期是否在指定范围内
*
* @param beginStr
* @param endStr
* @param date
* @return
* @throws ParseException
*/
public static boolean isTimeRange(String beginStr, String endStr, String date) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date time = sdf.parse(date);
SimpleDateFormat df = new SimpleDateFormat("HH:mm");
Date now = df.parse(df.format(time));
Date begin = df.parse(beginStr);
Date end = df.parse(endStr);
Calendar nowTime = Calendar.getInstance();
nowTime.setTime(now);
Calendar beginTime = Calendar.getInstance();
beginTime.setTime(begin);
Calendar endTime = Calendar.getInstance();
endTime.setTime(end);
if (nowTime.before(endTime) && nowTime.after(beginTime)) {
return true;
} else {
return false;
}
}
public static void main(String[] args) throws ParseException{
boolean bo = Test.isTimeRange("6:00","22:00","2021-11-11 08:12:25");
System.out.println("是否:" + bo);
}
}
一切美好的遇见都是命中注定~!