• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 55
  • Last Modified:

Create if statement with hour and minute in range

Dear all,

I am wanting to create an if statement, i.e. if between 9.30 and 11.00 do something.

I'm getting the hour and minute values from the calendar object.  

int hour = cal.get(Calendar.HOUR_OF_DAY);
int min = cal.get(Calendar.MINUTE);

Open in new window


Now that I'm using half hour data I'm unsure of how to update the if statement to check for hour and minute in range.

if ((hour >= 9) && (hour <= 11)) {
   value = 1;
}

Open in new window


Thanks
0
AndyC1000
Asked:
AndyC1000
  • 2
2 Solutions
 
chaauCommented:
You can use this:
if ((hour = 9 && min >= 30 || hour > 9) && (hour <= 11)) {
   value = 1;
}

Open in new window

0
 
AndyC1000Author Commented:
I have used your example,  for the hour 11 and minute 30  it is accessing the first  if statement when it shouldn't (only second). I made a change see below and it  still accesses both if statements.

Change to your example
if ((((hour == 9) && (minute >= 30)) || (hour > 9)) && (((hour == 11) && (minute == 0)) || (hour <= 11))) {			
value = 1;
}

if ((((hour == 11) && (minute >= 30)) || (hour > 11)) && (hour <= 13)) {
value = 2;
}

Open in new window

0
 
chaauCommented:
You are right, it needs more restrictions, like this:
if ((hour == 9 && min >= 30 || hour > 9) && (hour < 11 || hour == 11 && min == 0)) {
   value = 1;
}

Open in new window

0
 
mccarlIT Business Systems Analyst / Software DeveloperCommented:
With all your questions regarding date manipulation, I would seriously recommend looking at a library such as Joda-Time (http://www.joda.org/joda-time/) or moving to Java 8 (you're not already using 8 are you? I think I've asked this previously). It would make all this SO much easier and most importantly LESS chances for bugs.

If using a library (or moving to Java 8) is even a remote possibility, let me know and I can show you just how easy all this can become!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now