Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time comparison

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?

like image 568
sling Avatar asked Feb 22 '10 08:02

sling


People also ask

What are time differences called?

The local time within a time zone is defined by its offset (difference) from Coordinated Universal Time (UTC), the world's time standard.

How do you find the difference in time?

Calculate the duration between two times First, identify the starting and an ending time. The goal is to subtract the starting time from the ending time under the correct conditions. If the times are not already in 24-hour time, convert them to 24-hour time. AM hours are the same in both 12-hour and 24-hour time.

What is time difference?

(taɪm ˈdɪfrəns ) noun. the difference in clock time between two or more different time zones.

What is the best time difference?

Considering the 12 hours UTC and +14 hours UTC, the biggest time difference would be 26 hours, even beyond the theoretical 24 hours. So which places have a timezone difference of 26 hours? The answer would be the Howland Islands and the Republic of Kiribati's Line Islands.


1 Answers

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.

like image 61
Adam Batkin Avatar answered Sep 19 '22 19:09

Adam Batkin