Check if the time is within the min and max range

妖精的绣舞 提交于 2021-01-28 11:50:39

问题


I don't know what's happening here: I need to return true if the current time is between a given range, ex: now is 15:45:00 and is between 12:00:00(min) and 18:00:00(max), but this method is doing it wrong:

private boolean verifyIfInside(String max, String min){
    try {
        DateFormat dateFormat = new SimpleDateFormat ("HH:mm:ss");

        Date date = new Date();

        String hour1 = min;
        String hour2 = max;
        String newHour = dateFormat.format(date);

        Date minHour, maxHour, nowHour;
        minHour = dateFormat.parse(hora1);
        maxHour = dateFormat.parse(hora2);
        nowHour = dateFormat.parse(newHour );

        if ((minHour.compareTo(nowHour) <= 0) && (maxHour.compareTo(nowHour) >= 0)){
            return true;
        } else {
            return false;
        }
    } catch (ParseException parseException){
        parseException.printStackTrace();
        return false;
    }
}

回答1:


It works correctly with the suggested modifications:

  • Reverse the min and max parameters.
  • Use .before() and .after() to compare if the current hour is after min hour and before max hour.
  • To include the min/max time boundaries you can use: !nowHour.after(maxHour) && !nowHour.before(minHour);
  • To exclude the min/max time boundaries use this instead: nowHour.after(minHour) && nowHour.before(maxHour);
  • If you are constrained to an older version of java, consider using the appropriate java.time ThreeTen-Backport project as @Basil Bourque suggested. Otherwise, use the latest time API in Java 8+.

code:

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class scratch_21 {
    public static void main(String[] args) {
        System.out.println(verifyIfInside("14:00:00", "14:15:00"));
    }

    private static boolean verifyIfInside(String min, String max) {
        try {
            DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

            Date date = new Date();

            String hora1 = min;
            String hora2 = max;
            String newHour = dateFormat.format(date);

            Date minHour, maxHour, nowHour;
            minHour = dateFormat.parse(hora1);
            maxHour = dateFormat.parse(hora2);
            nowHour = dateFormat.parse(newHour);

            return  nowHour.after(minHour) && nowHour.before(maxHour);
        } catch (ParseException parseException) {
            parseException.printStackTrace();
            return false;
        }
    }
}



回答2:


I have tested it with .before() and .after() Its working fine and you can also reduce the code like:-

private static boolean verifyIfInside(String min , String max){
    try {
        DateFormat dateFormat = new SimpleDateFormat ("HH:mm:ss");

        String current_time = dateFormat.format(new Date());

        Date minHour = dateFormat.parse(min);
        Date maxHour = dateFormat.parse(max);
        Date curr_time = dateFormat.parse(current_time);

        return minHour.before(curr_time) && maxHour.after(curr_time);

    } catch (ParseException parseException){
        parseException.printStackTrace();
        return false;
    }
}



回答3:


  1. Time zone is crucial. Your verification makes no sense unless you know in which time zone you want the current time. For the reader’s sake, also specify it in your code.
  2. The date and time classes you use, Date, DateFormat and SimpleDateFormat, are not only long outdated, the last one in particular is also renowned for being troublesome to work with. Instead I recommend you use java.time, the modern Java date and time API. This even furnishes a LocalTime class, a time of day without a date, which matches your need much more precisely than Date.

So your method is written clearly and tersely thus:

private static boolean verifyIfInside(String max, String min) {
    LocalTime now = LocalTime.now(ZoneId.of("Europe/Budapest"));
    LocalTime minHour = LocalTime.parse(min);
    LocalTime maxHour = LocalTime.parse(max);
    return ! (now.isBefore(minHour) || now.isAfter(maxHour));
}

Please substitute your desired time zone if it didn’t happen to be Europe/Budapest.

Since I understood that you wanted your range to be inclusive, and since isBefore and isAfter mean strictly before and after, I used a negation to test that the time is “not outside the range”.

I am furthermore exploiting the fact that your time format, 12:00:00, agrees with ISO 8601, the format that the modern classes parse as their default, that is, without any explicit formatter. A potential downside is that validation of the time strings is weaker: parse() will also accept 12:00 and 12:23:29.82376342. If you need to reject these as errors, you do need an explicit formatter.

What went wrong in your code?

As far as I can tell, your code in the question is working correctly (if we just change hora1 to hour1 or the other way around, and hora2 too). You may have been confused about the order of the arguments. The following returns true if run between 12 and 18: verifyIfInside("18:00:00", "12:00:00"). However, many would find it natural to write the call as verifyIfInside("12:00:00", "18:00:00"), which returns false always. So it would almost surely be better to declare the method as verifyIfInside(String min, String max), that is, with min before max.

Another possibility is, of course, as I mentioned, that your JVM is using a different time zone from the one you think it is using. This would very likely give you unexpected results. The only way to be sure this is not the case is to specify explicitly which time zone it should use.



来源:https://stackoverflow.com/questions/48232340/check-if-the-time-is-within-the-min-and-max-range

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!