如何在Java中查找请求的时间是否介于时间范围之间
我以字符串格式输入了日期(例如:-如何在Java中查找请求的时间是否介于时间范围之间,java,date,datetime,java-time,Java,Date,Datetime,Java Time,我以字符串格式输入了日期(例如:-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
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")
java.util.Date inputDate=新的SimpleDateFormat(“yyyy-MM-dd'T:HH:MM:ss”).parse(“2020-01-08T07:00:00”);
if(inputDate.getTime()<“06:00”和&inputDate.getTime()>“15:00”)
但它显然无法与字符串进行比较,因此我不知道如何比较?请避免使用遗留日期库,我建议使用如下方式:
// 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))) {
}
请避免使用遗留日期库,我建议您这样使用:
// 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))) {
}
不要使用旧的日期Api。使用
java.time
api也可以:“06:00”是一个字符串,而不是时间中的某个时刻将其解析为ZonedDateTime;将其转换为LocalDateTime;从中获取本地时间;将本地时间与您的范围进行比较。我建议您不要使用SimpleDateFormat
和Date
。这些类设计得很糟糕,而且早已过时,其中前者尤其令人讨厌。而是使用LocalDateTime
和LocalTime
,这两种方法都来自。请参阅YCF_L的正确答案。不要使用旧的日期Api。使用java.time
api也可以:“06:00”是一个字符串,而不是时间中的某个时刻将其解析为ZonedDateTime;将其转换为LocalDateTime;从中获取本地时间;将本地时间与您的范围进行比较。我建议您不要使用SimpleDateFormat
和Date
。这些类设计得很糟糕,而且早已过时,其中前者尤其令人讨厌。而是使用LocalDateTime
和LocalTime
,这两种方法都来自。请看YCF_L的好答案。DateTimeFormatter来自org.joda.time.format.DateTimeFormatter,对吗?这意味着类型的ofPattern(字符串)未定义DateTimeFormatter@JavaSSE,是的,但我指的java时间DateTimeFormatter来自org.joda.time.format.DateTimeFormatter,对吗?这意味着类型的ofPattern(字符串)未定义DateTimeFormatter@JavaSSE,是的,但我指的是java时间