Search code examples
javatimejava-timelocaltimedatetimeformatter

Sum hours and minutes together Java


Summing hours and minutes together results in the wrong answer.

Here are 2 lists with hours.

[[0 hours : 0 mins : 0 sec, 1 hours : 16 mins : 22 sec, 0 hours : 1 mins : 53 sec, 23 hours : 54 mins : 18 sec], [0 hours : 8 mins : 22 sec, 0 hours : 8 mins : 22 sec, 0 hours : 8 mins : 22 sec]]this is HOURS

Then, I divide it into sublists, to calculate for each. Here is one of the sublists.

[0 hours : 0 mins : 0 sec, 1 hours : 16 mins : 22 sec, 0 hours : 1 mins : 53 sec, 23 hours : 54 mins : 18 sec]

So, the answer I get for this sublist is: 1 hours:12 minutes:33 seconds, which is incorrect. I suppose to get around 25 hours plus a few minutes.

public List<String> getTheHoursWorked() {
    DateTimeFormatter parser = DateTimeFormatter.ofPattern("H 'hours :' m 'mins :' s 'sec'", Locale.US);
    final DateFormat dt = new SimpleDateFormat("HH:mm:ss");
    final Calendar c = Calendar.getInstance(TimeZone.getDefault(), Locale.getDefault());

    c.clear();
    long startingMS = c.getTimeInMillis();
    int counter = 0;

    for (int k = 0; k < hours.size(); k++){
        List<Object> shorter = new ArrayList<>();
        List<Object> temp;
        temp = (List<Object>) hours.get(k);
        
        long milliseconds = 0;
        for (int m = 0; m < shorter.size(); m++) {
            LocalTime odt = LocalTime.parse((CharSequence) shorter.get(m), parser);
            DateTimeFormatter formatter =
                    DateTimeFormatter.ofPattern("HH:mm:ss");
            String printDate = formatter.format(odt);
            try {
                milliseconds = milliseconds + (dt.parse(printDate).getTime() - startingMS);
                System.out.println(milliseconds + "MILISECONDS");
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        hoursToString.add(String.valueOf(shorter));
        String s = milliseconds / 1000 % 60   + " seconds";
        String m = milliseconds /(60 * 1000) % 60 + " minutes";
        String h = milliseconds / (60 * 60 * 1000) % 24 + " hours";
        String together = h+":"+m+":"+s;
        togetherHours.add(together);
    }
    return togetherHours;
}

Solution

  • The steps of the solution should be

    1. Start with a time of 0:0
    2. Iterate the list and add all hours, minutes and seconds separately after parsing the time strings using the corresponding formatter.
    3. Adjust hour, minutes and seconds if minute and/or second exceed 60.

    Demo:

    import java.time.LocalTime;
    import java.time.format.DateTimeFormatter;
    import java.util.List;
    
    public class Main {
        public static void main(String[] args) {
            List<String> list = List.of("0 hours : 0 mins : 0 sec", "1 hours : 16 mins : 22 sec",
                    "0 hours : 1 mins : 53 sec", "23 hours : 54 mins : 18 sec");
    
            // Start with a time of 0:0
            int sumHours = 0;
            int sumMinutes = 0;
            int sumSeconds = 0;
    
            // Iterate the list and add all hours, minutes and seconds separately after
            // parsing the time strings using the corresponding formatter
            DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("H' hours : 'm' mins : 's' sec'");
            for (String strTime : list) {
                LocalTime time = LocalTime.parse(strTime, timeFormatter);
                sumHours += time.getHour();
                sumMinutes += time.getMinute();
                sumSeconds += time.getSecond();
            }
    
            // Adjust hour, minutes and seconds if minute and/or second exceed 60
            sumMinutes += sumSeconds / 60;
            sumSeconds %= 60;
            sumHours += sumMinutes / 60;
            sumMinutes %= 60;
    
            String strSum = String.format("%d hours : %d mins : %d sec", sumHours, sumMinutes, sumSeconds);
            System.out.println(strSum);
        }
    }
    

    Output:

    25 hours : 12 mins : 33 sec