我正在尝试确定当前时间(例如 19:30:00(是否在第二天 19:00:00 和 03:00:00 之间,但我的代码失败了。 我的代码在此情况下失败 如果是,我可以使用日期到露营时间,请告诉我如何
import java.util.Calendar;
import java.text.SimpleDateFormat;
public class DateUtils {
// format 24hre ex. 12:12 , 17:15
private static String HOUR_FORMAT = "HH:mm";
private DateUtils() { }
public static String getCurrentHour() {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdfHour = new SimpleDateFormat(HOUR_FORMAT);
String hour = sdfHour.format(cal.getTime());
return hour;
}
/**
* @param target hour to check
* @param start interval start
* @param end interval end
* @return true true if the given hour is between
*/
public static boolean isHourInInterval(String target, String start, String end) {
return ((target.compareTo(start) >= 0)
&& (target.compareTo(end) <= 0));
}
/**
* @param start interval start
* @param end interval end
* @return true true if the current hour is between
*/
public static boolean isNowInInterval(String start, String end) {
return DateUtils.isHourInInterval
(DateUtils.getCurrentHour(), start, end);
}
// TEST
public static void main (String[] args) {
String now = DateUtils.getCurrentHour();
String start = "14:00";
String end = "14:26";
System. out.println(now + " between " + start + "-" + end + "?");
System. out.println(DateUtils.isHourInInterval(now,start,end));
/*
* output example :
* 21:01 between 14:00-14:26?
* false
*
*/
}
}
java.time.LocalTime是你的朋友。下面是一个快速示例,当然可以做得更短一些。
void test(){
var tz = ZoneId.of("CET");
var anyDate = LocalDate.of(2019,12,4);
var x = ZonedDateTime.of(LocalDateTime.of(anyDate, LocalTime.of(18,59)),tz).toInstant();
System.out.println(testTime(Clock.fixed( ZonedDateTime.of(LocalDateTime.of(anyDate, LocalTime.of(18,59)),tz).toInstant(),tz)));
System.out.println(testTime(Clock.fixed( ZonedDateTime.of(LocalDateTime.of(anyDate, LocalTime.of(19,01)),tz).toInstant(),tz)));
System.out.println(testTime(Clock.fixed( ZonedDateTime.of(LocalDateTime.of(anyDate, LocalTime.of(00,00)),tz).toInstant(),tz)));
System.out.println(testTime(Clock.fixed( ZonedDateTime.of(LocalDateTime.of(anyDate, LocalTime.of(02,59)),tz).toInstant(),tz)));
System.out.println(testTime(Clock.fixed( ZonedDateTime.of(LocalDateTime.of(anyDate, LocalTime.of(03,01)),tz).toInstant(),tz)));
}
boolean testTime(Clock clock){
var evening =LocalTime.of(19,00);
var midnight =LocalTime.of(00,00);
var night =LocalTime.of(03,00);
LocalTime wallTime = LocalTime.now(clock);
return (wallTime.isAfter(evening) && wallTime.isBefore(midnight.minusNanos(1))) || (midnight.isBefore(wallTime) && wallTime.isBefore(night)) || wallTime.equals(midnight);
}