I have a time in hh:mm and it has to be entered by the user in that format.
However, I want to compare the time (eg. 11:22) is it between 10am to 6pm? But how do I compare it?
I have a time in hh:mm and it has to be entered by the user in that format.
However, I want to compare the time (eg. 11:22) is it between 10am to 6pm? But how do I compare it?
From your statement, it seems like you merely want to write:
if (10 >= hh && hh < 18) {
...
}
This is trivial if you are given the hours already. But surely you are asking something else?
example:
import java.util.*;
import java.lang.Object;
import java.text.Collator;
public class CurrentTime{
public class CurrentTime
{
public static void main( String[] args )
{
Calendar calendar = new GregorianCalendar();
String am_pm;
int hour = calendar.get( Calendar.HOUR );
int minute = calendar.get( Calendar.MINUTE );
// int second = calendar.get(Calendar.SECOND);
if( calendar.get( Calendar.AM_PM ) == 0 ){
am_pm = "AM";
if(hour >=10)
System.out.println( "welcome" );
}
else{
am_pm = "PM";
if(hour<6)
System.out.println( "welcome" );
}
String time = "Current Time : " + hour + ":" + minute + " " + am_pm;
System.out.println( time );
}
}
Java doesn't (yet) have a good built-in Time
class (it has one for JDBC queries, but that's not what you want).
One option would be use the JodaTime APIs and its LocalTime class.
Sticking with just the built-in Java APIs, you are stuck with java.util.Date. You can use a SimpleDateFormat to parse the time, then the Date
comparison functions to see if it is before or after some other time:
SimpleDateFormat parser = new SimpleDateFormat("HH:mm");
Date ten = parser.parse("10:00");
Date eighteen = parser.parse("18:00");
try {
Date userDate = parser.parse(someOtherDate);
if (userDate.after(ten) && userDate.before(eighteen)) {
...
}
} catch (ParseException e) {
// Invalid date was entered
}
Or you could just use some string manipulations, perhaps a regular expression to extract just the hour and the minute portions, convert them to numbers and do a numerical comparison:
Pattern p = Pattern.compile("(\d{2}):(\d{2})");
Matcher m = p.matcher(userString);
if (m.matches() ) {
String hourString = m.group(1);
String minuteString = m.group(2);
int hour = Integer.parseInt(hourString);
int minute = Integer.parseInt(minuteString);
if (hour >= 10 && hour <= 18) {
...
}
}
It really all depends on what you are trying to accomplish.
The following assumes that your hours and minutes are stored as ints in variables named hh and mm respectively.
if ((hh > START_HOUR || (hh == START_HOUR && mm >= START_MINUTE)) &&
(hh < END_HOUR || (hh == END_HOUR && hh <= END_MINUTE))) {
...
}