如何查找请求的时间是否在 Java 的时间范围内
How to find if requested time is between timerange in Java
我有字符串格式的日期输入(例如:- 2020-01-08T07:00:00
),我想检查输入时间是否在 6:00
到 15:00
之间。
知道我该如何检查吗?
我试过下面的代码:-
java.util.Date inputDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").parse("2020-01-08T07:00:00");
if(inputDate.getTime() < "06:00" && inputDate.getTime() > "15:00")
但显然不能和String比较,所以我很困惑如何比较它?
请避免使用遗留日期库,我建议像这样使用 java.time
:
// format your date time by using the default formater of LocalDateTime
LocalDateTime ldt = LocalDateTime.parse("2020-01-08T07:00:00");
// Get the time part from your LocalDateTime
LocalTime lt = ldt.toLocalTime();
// create a patter to format the two times
DateTimeFormatter hmFormatter = DateTimeFormatter.ofPattern("H:mm");
// use isAfter and isBefore to check if your date in the range you expect
if (lt.isAfter(LocalTime.parse("6:00", hmFormatter)) &&
lt.isBefore(LocalTime.parse("15:00", hmFormatter))) {
}
我有字符串格式的日期输入(例如:- 2020-01-08T07:00:00
),我想检查输入时间是否在 6:00
到 15:00
之间。
知道我该如何检查吗?
我试过下面的代码:-
java.util.Date inputDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").parse("2020-01-08T07:00:00");
if(inputDate.getTime() < "06:00" && inputDate.getTime() > "15:00")
但显然不能和String比较,所以我很困惑如何比较它?
请避免使用遗留日期库,我建议像这样使用 java.time
:
// format your date time by using the default formater of LocalDateTime
LocalDateTime ldt = LocalDateTime.parse("2020-01-08T07:00:00");
// Get the time part from your LocalDateTime
LocalTime lt = ldt.toLocalTime();
// create a patter to format the two times
DateTimeFormatter hmFormatter = DateTimeFormatter.ofPattern("H:mm");
// use isAfter and isBefore to check if your date in the range you expect
if (lt.isAfter(LocalTime.parse("6:00", hmFormatter)) &&
lt.isBefore(LocalTime.parse("15:00", hmFormatter))) {
}