Calculate Difference between two times in Android

Solution 1:

Try below code.

// suppose time format is into ("hh:mm a") format

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm a");

date1 = simpleDateFormat.parse("08:00 AM");
date2 = simpleDateFormat.parse("04:00 PM");

long difference = date2.getTime() - date1.getTime(); 
days = (int) (difference / (1000*60*60*24));  
hours = (int) ((difference - (1000*60*60*24*days)) / (1000*60*60)); 
min = (int) (difference - (1000*60*60*24*days) - (1000*60*60*hours)) / (1000*60);
hours = (hours < 0 ? -hours : hours);
Log.i("======= Hours"," :: "+hours);

Output - Hours :: 8

Solution 2:

Note: Corrected code as below which provide by Chirag Raval because in code which Chirag provided had some issues when we try to find time from 22:00 to 07:00.

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
Date startDate = simpleDateFormat.parse("22:00");
Date endDate = simpleDateFormat.parse("07:00");

long difference = endDate.getTime() - startDate.getTime(); 
if(difference<0)
{
    Date dateMax = simpleDateFormat.parse("24:00");
    Date dateMin = simpleDateFormat.parse("00:00");
    difference=(dateMax.getTime() -startDate.getTime() )+(endDate.getTime()-dateMin.getTime());
}
int days = (int) (difference / (1000*60*60*24));  
int hours = (int) ((difference - (1000*60*60*24*days)) / (1000*60*60)); 
int min = (int) (difference - (1000*60*60*24*days) - (1000*60*60*hours)) / (1000*60);
Log.i("log_tag","Hours: "+hours+", Mins: "+min); 

Result will be: Hours: 9, Mins: 0