In my app I create an object that represents a high school class. This object holds 2 Calendar objects that represents the class\'s start and stop time each day. When a user c
The Calendar class has a get
method where you can get
different fields
e.g.
int hr = time.get(Calendar.HOUR_OF_DAY)
I will here only provide the Joda-Time-related answer you asked for. Joda-Time has the advantage to offer a dedicated type for the clock time, namely LocalTime. The old java.util.Calendar
-stuff does not offer this advantage hence your difficulties.
First you convert an instance of java.util.Date
like follows:
Date time = ...;
DateTime dt = new DateTime(time, DateTimeZone.getDefault());
LocalTime lt = dt.toLocalTime();
Note that the conversion is always timezone dependent. Then you can compare two LocalTime
instances using the inherited methods isAfter(...)
or isBefore(...)
.
JDK 8 Date-Time APIs are a good approach to solving these kinds of issues. Instead of Calendar , use LocalTime to store the start and end time of the class.
LocalTime now = LocalTime.now(ZoneId.systemDefault());
LocalTime start = mList.get(a).getStartTime();
LocalTime end = mList.get(a).getEndTime();
if(now.isAfter(start) && now.isBefore(end)){
//do something
}
For Android, you can use The ThreeTenABP project which adapts the java.time APIs for Android.
You can use Calendar.get()
, as mentioned in another answer. To compare minutes, though, you should use Calendar.MINUTE, too:
int minutes_in_day = time.get(Calendar.HOUR_OF_DAY)*60 + time.get(Calendar.MINUTE);
Then, you can just compare the minutes within the day of the current time with that of the start and end times. This will, of course, only work when the times are in the same day.
try {
Date date1 = sdf.parse(given time);
Date date2 = sdf.parse("08:00 AM");
Date date3 = sdf.parse("06:00 PM");
if((date1.after(date2))&&(date1.before(date3))||date1.equals(date2) ||date1.equals(date3) ) {
}
} catch (ParseException e){
e.printStackTrace();
}