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?
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.
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.
This is what I do: long diff = date1. getTime() - date2. getTime(); Date diffDate = new Date(diff);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With