midders
midders

Reputation: 57

Android - sum of multiple lengths of time in HH:mm

I have been struggling to get the sum of two lengths of time in hours and mins and I realise this has likely been covered many times but I must be looking in the wrong place. I am trying to find the sum of time spent driving. So someone wrote on a timecard they drove from 0902 to 1105, had a break and the drove from 1156 to 1541. I have it so it calculates the individual times spent driving, 02:03 and 03:45 but I need to add those times together.

I know I could just do the maths but I would prefer to use the same method for calculating the individual times but with addition rather than subtraction. It adds the minutes correctly but doesn't add the hours from the first time. So the sum of the above times is shown as 03:48.

Or if the times were 02:31 and 03:50 the total would show as 4:21. Any help would be appreciated.

//Total1 = 02:31 Total2 = 03:50 but sum of both only = 4:21  not 6:21 doesn't add first time hours to total

    try {
        datec = simpleDateFormat.parse(Total1);
        }catch(ParseException pe){
            shiftHours.setText("err");
        } catch (java.text.ParseException e) {
            shiftHours.setText("err");
        }
        catch(NullPointerException npe) {
            shiftHours.setText("err");
        }


    try {
        dated = simpleDateFormat.parse(Total2);
        }catch(ParseException pe){
            shiftHours.setText("err");
        } catch (java.text.ParseException e) {
            shiftHours.setText("err");
        }
        catch(NullPointerException npe) {
            shiftHours.setText("err");
        }

    long tdifference = dated.getTime() + datec.getTime();
    int tdays = (int) (tdifference / (1000*60*60*24));  
    int thours = (int) ((tdifference - (1000*60*60*24*tdays)) / (1000*60*60)); 
    int tmin = (int) (tdifference - (1000*60*60*24*tdays) - (1000*60*60*thours)) / (1000*60);
    String dh = Integer.toString(thours);
    String dm = Integer.toString(tmin);

    shiftHours.setText(dh);
    shiftMins.setText(dm);

Upvotes: 1

Views: 531

Answers (1)

youssefhassan
youssefhassan

Reputation: 1065

The problem that you are summing two clock times 3:50am and 2:31am in milliseconds which is irrelevant.

The correct way is to convert the duration to units like 3:50 is 3+50/60 and 2:31 is 2 + 31/60 that will give you the number of hours.

that will give 6.35 which should be converted to 6:(35*60)/100 which is 6:21 hours.

Hope it is clear

Upvotes: 1

Related Questions