1

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;
    }
}
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • 4
    Use `Date.before()` and `Date.after()` instead of converting your times to strings and using String comparison. Also, you pass `max, min` in that order, but `hour1, hour2` correspond to `min, max`. Are you passing the parameters in the right order? – Welbog Jan 12 '18 at 18:51
  • 1
    `hour1` is probably a - for us - translated `hora1` a bit further on. And indeed the parameters are defined as `(max, min)` a bit counter-intuitive. – Joop Eggen Jan 12 '18 at 19:08
  • Any particular reason why you are using the long outdated classes `DateFormat`, `SimpleDateFormat` and `Date`? Rather than that trouble I recommend you use [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). It is so much nicer to work with. – Ole V.V. Jan 12 '18 at 23:11
  • Possible duplicate of [How to know if now time is between two hours?](https://stackoverflow.com/questions/17212848/how-to-know-if-now-time-is-between-two-hours) – Ole V.V. Jan 12 '18 at 23:14

3 Answers3

0

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;
    }
}
Ravindra Kumar
  • 1,842
  • 14
  • 23
0
  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.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
-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;
        }
    }
}
egallardo
  • 1,234
  • 1
  • 15
  • 25
  • 2
    A code dump is not a useful answer, as it requires readers to scan all of your code and try to determine what you did to solve the problem. Your answer would be better if you explained what you changed, and why. – VGR Jan 12 '18 at 19:12
  • @egallardo The founders of Stack Exchange intended this site to be a learning/teaching resource, not just a code snippet collection. – Basil Bourque Jan 13 '18 at 04:20
  • @BasilBourque So, teach me what's wrong with what I posted. I explained the modifications and posted a fixed version that the OP found useful. What's wrong with that? – egallardo Jan 16 '18 at 15:16
  • 1
    @egallardo Much better. I removed my down-vote. Two milder criticisms: (a) in 2018 we should not be teaching the use of the troublesome old date-time classes that are now legacy, supplanted entirely by the *java.time* classes. (b) Your recommendation of Joda-Time is outdated as well. That project is now in maintenance mode, with its team advising migration to the *java.time* classes. For Java 6 & Java 7, use the *ThreeTen-Backport* project. For earlier Android, use the *ThreeTenABP* project. – Basil Bourque Jan 16 '18 at 16:53