How to add n hours in java

I have n no of times.

ex:-

01:00:06

02:30:00

05:00:09

01:59:06

10:15:06

I want to add all this times. Finally calculate how may hours, min and seconds.

Please let me an idea to solve this.

I ma trying to do this using Calendar.

Updated:-

private void test() {

        String[] dates = { "01:00:06", "02:30:00", "05:00:09", "01:59:06",
                "10:15:06" };

        Calendar calendar1 = Calendar.getInstance();
        Calendar calendar2 = Calendar.getInstance();
        Calendar calendar = Calendar.getInstance();
        long totalHours;

        for (int i = 0; i < dates.length; i++) {

            calendar.setTime(ConstantFunction.StringToDate("HH:mm:ss",
                    dates[i]));
            int hours = calendar.get(Calendar.HOUR_OF_DAY);
            int minutes = calendar.get(Calendar.MINUTE);
            int seconds = calendar.get(Calendar.SECOND);

            if (i == 0) {
                calendar1.add(Calendar.HOUR_OF_DAY, hours);
                calendar1.add(Calendar.MINUTE, minutes);
                calendar1.add(Calendar.SECOND, seconds);
            } else {
                calendar2.add(Calendar.HOUR_OF_DAY, hours);
                calendar2.add(Calendar.MINUTE, minutes);
                calendar2.add(Calendar.SECOND, seconds);
            }
        }
        long diffInMilis = calendar2.getTimeInMillis()
                - calendar1.getTimeInMillis();

        long diffInSecond = diffInMilis / 1000;
        long diffInMinute = diffInMilis / (60 * 1000)% 60;
        long diffInHour = diffInMilis / (60 * 60 * 1000);
        System.out.println("diffInSecond==> " + diffInSecond);
        System.out.println("diffInMinute==> " + diffInMinute);
        System.out.println("diffInHour==> " + diffInHour);
    }

I am do like this. But here I am getting wrong output.

diffInSecond==> 67455
diffInMinute==> 44
diffInHour==> 18

Upvotes: 2

Views: 90

Answers (1)

Finally I conclude with this solution. But I don't know this is a correct way to do this. Bu I got expected OP.

private void test() {

        String[] dates = { "01:00:06", "02:30:00", "05:00:09", "01:59:06",
                "10:15:06" };
        long totalSecs=0;
        for(int i=0;i<dates.length;i++){
            totalSecs+=GetSeconds(dates[i]);
        }

        long hours = totalSecs / 3600;
        long minutes = (totalSecs % 3600) / 60;
        long seconds = totalSecs % 60;

        System.out.println("hours==> " + hours);
        System.out.println("minutes==> " + minutes);
        System.out.println("seconds==> " + seconds);

    }

    private long GetSeconds(String time){
        String[] parts = time.split(":");
        long totSec=0;
        int hour=Integer.parseInt(parts[0]);
        int min=Integer.parseInt(parts[1]);
        int sec=Integer.parseInt(parts[2]);

        totSec=(hour*3600)+(min*60)+sec;

        return totSec;
    }

Upvotes: 1

Related Questions