Girish Bellamkonda
Girish Bellamkonda

Reputation: 501

Sum time using java in HH:MM format

I am trying to add the daily working hours for an employee for a duration of a week.

Ex: if an employee worked as Below in HH:MM format

Monday      09:45
Tuesday     10:00
Wednesday   09:00
Thursday    09:30
Friday      10:00
----------------------------
Total       48:15
----------------------------

I need to sum the week timings to generate payroll hours. How I could do this using java.

Could you please help with this ? thanks a lot !!

Upvotes: 1

Views: 2800

Answers (2)

injecteer
injecteer

Reputation: 20699

I'd put it like that:

int sum = 0
for( String hhmm : workingTimes ){
  String[] split = hhmm.split( ":", 2 );
  int mins = Integer.valueOf(split[ 0 ]) * 60 + Integer.valueOf( split[ 1 ] );
  sum += mins;
}

String formattedWorkingTime = (int)Math.floor(sum/60) + ":" + ( sum % 60 );

Upvotes: 4

Sanjeev
Sanjeev

Reputation: 9946

You can use something like this:

public static String totalTime(String...times) {
    int total = 0;
    for (String time : times) {
        String[] splits = time.split(":");
        total+=(Integer.parseInt(splits[0])*60 + Integer.parseInt(splits[1]));
    }

    return total/60 + ":" + total%60;
}

or

Alternatively You can also use Java 8 Time API

Upvotes: 0

Related Questions