Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate Difference between two times in Android

I have two string variables such as StartTime and EndTime. I need to Calculate the TotalTime by subtracting the EndTime with StartTime.

The Format of StartTime and EndTime is as like follows:

StartTime = "08:00 AM";
EndTime = "04:00 PM";

TotalTime in Hours and Mins Format. How to calculate this in Android?

like image 353
Munazza Avatar asked Jan 01 '13 12:01

Munazza


People also ask

How can I get the difference between two time in Android?

I need to Calculate the TotalTime by subtracting the EndTime with StartTime. The Format of StartTime and EndTime is as like follows: StartTime = "08:00 AM"; EndTime = "04:00 PM"; TotalTime in Hours and Mins Format.

How do you find the difference in time between two times?

Calculate the duration between two times 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.

How does kotlin get time difference?

This is what I do: long diff = date1. getTime() - date2. getTime(); Date diffDate = new Date(diff);


1 Answers

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

like image 61
Kalpesh Avatar answered Sep 30 '22 00:09

Kalpesh