简体   繁体   中英

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 !!

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 );

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM