aresz
aresz

Reputation: 2649

Getting values from 2 TimePickers and comparing them

In my application, I have setup 2 TimePickers inside my activity. This is currently how I get the values from the 2 TimePickers:

int hour1 = mFirstWakeUpTimePicker.getCurrentHour();
int min1 = mFirstWakeUpTimePicker.getCurrentMinute();
int hour2 = mSecondWakeUpTimePicker.getCurrentHour();
int min2 = mSecondWakeUpTimePicker.getCurrentMinute();

GregorianCalendar calendar1 = new GregorianCalendar();
GregorianCalendar calendar2 = new GregorianCalendar();

calendar1.set(Calendar.HOUR_OF_DAY, hour1);
calendar1.set(Calendar.MINUTE, min1);
calendar2.set(Calendar.HOUR_OF_DAY, hour2);
calendar2.set(Calendar.MINUTE, min2);

After that, I need to compare them to check if they are at least 3 minutes apart. How do I achieve this? Also, what's the better way of writing this code?

Any help is appreciated.

Upvotes: 0

Views: 42

Answers (3)

LucioB
LucioB

Reputation: 1754

Assuming you want calendar2 to be late then three mins with respect to calendar1 you can do like this, right after getting hours and mins from Timepickers:

GregorianCalendar calendar1 = new GregorianCalendar();
GregorianCalendar calendar2 = new GregorianCalendar();

calendar1.set(Calendar.HOUR_OF_DAY, hour1);
calendar1.set(Calendar.MINUTE, min1);
calendar2.set(Calendar.HOUR_OF_DAY, hour2);
calendar2.set(Calendar.MINUTE, min2);

long millisCal1 = calendar1.getTimeInMillis();
long millisCal2 = calendar2.getTimeInMillis();

if (millisCal2 - millisCal1 >= 1000 * 60 * 3){
    // They differ of at least three mins
} else {
    // They not differ of at least three mins
}

Where three mins is translated in millis 1000 * 60 * 3. If you want to check calendar1 later than calendar2 just switch the order inside the if statement.

Bye

Upvotes: 1

wislie
wislie

Reputation: 101

you could compare calendar1 with calendar2 by using method "calendar.getTimeInMillis()",as following:

int minutes = (int) ((calendar2.getTimeInMillis()-calendar1.getTimeInMillis())/(1000 * 60)) ;

Upvotes: 1

Rakshit Nawani
Rakshit Nawani

Reputation: 2604

If you have two date you can check these by the following conditions:

if(calendar1.isBefore(calendar2)){ // conditions here }

and you can also check the same for isAfter

OR if you want to check for atleast 3 minutes add the dates and then comapre them like:

Calendar calendar = Calendar.getInstance(); calendar.setTime(dat1); calendar.add(Calendar.MINUTE, dat2);

Try this and let me know if it helps.

Upvotes: 0

Related Questions