How to compare current time with time range?

Viewed 53714

I have two String variables - time1 and time2. Both contain value in the format HH:MM. How can I check:

  1. If the current time is within time1 and time2?
  2. time1 will happen in the nearest hour?

Upd. I've implemented the following to convert time1 to Date format. But it uses depreciated methods:

Date clTime1 = new Date();

SimpleDateFormat timeParser = new SimpleDateFormat("HH:mm", Locale.US);
try {
  clTime1 = timeParser.parse(time1);
} catch (ParseException e) {
}

Calendar now = Calendar.getInstance();
clTime1.setYear(now.get(Calendar.YEAR) - 1900);
clTime1.setMonth(now.get(Calendar.MONTH));
clTime1.setDate(now.get(Calendar.DAY_OF_MONTH));
System.out.println(clTime1.toString());
9 Answers

if you want time between after 9PM to before 9Am you can use following condition..

if(cal.get(Calendar.HOUR_OF_DAY)> 20 || cal.get(Calendar.HOUR_OF_DAY)< 9)
{
    // do your stuffs
}
class TimeRange {

    LocalTime from;
    LocalTime to;

    public TimeRange(LocalTime from, LocalTime to) {
        this.from = from;
        this.to = to;
    }

    public boolean isInRange(Date givenDate) {

        LocalTime givenLocalTime = getLocalDateTime(givenDate).toLocalTime();
        return givenLocalTime.isAfter(from) && givenLocalTime.isBefore(to);
    }

    public static LocalDateTime getLocalDateTime(Date date){

        return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
    }
}
Related