Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare current time with time range?

Tags:

java

time

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());
like image 319
LA_ Avatar asked Jun 16 '11 19:06

LA_


People also ask

How to compare current time with specific time in Java?

time classes built into Java, specifically LocalTime . Get the current time-of-day in your local time zone. Construct a time-of-day per your input string. Compare with the isBefore , isAfter , or isEqual methods.


1 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
}
like image 85
Abhay Pratap Avatar answered Oct 20 '22 22:10

Abhay Pratap