您好我有一个时间列表,但我想根据时间列表检查时间是天周期还是夜间周期。
尝试{
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");
Date date_from = formatter.parse("00:00");
Date date_to = formatter.parse("12:00");
Date dateNow = formatter.parse("07:30");
if (date_from.before(dateNow)) {
check = "nightCycle";
} else if (dateNow.before(date_to)) {
check = "nightCycle";
} else if (dateNow.after(date_from)) {
check = "nightCycle";
} else {
check = "DayCycle";
}
} catch (Exception e) {
e.printStackTrace();
}
答案 0 :(得分:1)
您需要根据午夜时间间隔使用不同的条件。画一个小图,这有助于使条件正确。
if (date_from.before(date_to)) { // they are on the same day
if (dateNow.after(date_from) && dateNow.before(date_to)) {
check = "nightCycle";
} else {
check = "dayCycle";
}
} else { // interval crossing midnight
if (dateNow.before(date_to) || dateNow.after(date_from)) {
check = "nightCycle";
} else {
check = "dayCycle";
}
}
答案 1 :(得分:0)
Just in case any one wants a complete working code modified henry and Shanmugapriyan's solutions a little bit.
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");
Date date_from = formatter.parse("00:00");
Date date_to = formatter.parse("08:00");
Date dateNow = formatter.parse(formatter.format(new Date()));
System.out.println("date_to: " + date_from);
System.out.println("date_to: " + date_to);
System.out.println("dateNow: " + dateNow);
String check = "dayCycle";
if (date_from.before(date_to)) { // they are on the same day
if (dateNow.after(date_from) && dateNow.before(date_to)) {
check = "nightCycle";
} else {
check = "dayCycle";
}
} else { // interval crossing midnight
if (dateNow.before(date_to) || dateNow.after(date_from)) {
check = "nightCycle";
} else {
check = "dayCycle";
}
}
System.out.println("Cycle is " + check);