Medlin Moni
Medlin Moni

Reputation: 99

How to sum total number of hours ,minutes,seconds in java?

Am having a doubt on how to sum total number of hours minutes seconds in java for example i have 160:00:00 and 24:00:00 and 13:50:00 and 00:10:00 i need to get grand sum like 198:00:00 how can i calculate this so far what i have tried is

 for(int i=0;i<addnoteobj.size();i++){


            String s =  addnoteobj.get(i).getDuration();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
            simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
            String[] tokens = s.split(":");
            int hours = Integer.parseInt(tokens[0]);
            int minutes = Integer.parseInt(tokens[1]);
            int seconds = Integer.parseInt(tokens[2]);
             duration = 3600 * hours + 60 * minutes + seconds;
           int j = duration/3600;
           int h= (duration%3600) / 60;
           int m = (duration % 60);


           hourss=hourss+j;
           mm=mm+h;
           sss=sss+m;

           date3 = hourss + ":" + mm + ":" + ss;
            String time = simpleDateFormat.format(new Date(duration*1000L));
            Log.d("dat",time);


            try {
                    date=simpleDateFormat.parse(s);
                    ss=ss+date.getTime();
                    date3 = simpleDateFormat.format(new Date(ss));
                  // total=dates.getTime();
                    Log.d("time",date3);
                } catch (ParseException e) {
                    e.printStackTrace();
                }


        }

But i cannot achieve this how to do this am having total hours in list how to get total hours thanks in advance

Upvotes: 0

Views: 3386

Answers (3)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79245

java.time

The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.

Solution using java.time, the modern Date-Time API:

You can use java.time.Duration which is modelled on ISO-8601 standards and was introduced with Java-8 as part of JSR-310 implementation. With Java-9 some more convenient methods were introduced.

Assuming all the string are in the form of HH:mm:ss format, you can split them on : and then combine the parts to form a string in the ISO 8601 pattern for a duration which can be parsed using Duration#parse.

Demo:

import java.time.Duration;

public class Main {
    public static void main(String[] args) {
        String[] strDurationArr = { 
                "160:00:00", 
                "24:00:00", 
                "13:50:00", 
                "00:10:00" 
        };

        Duration sum = Duration.ZERO;
        for (String strDuration : strDurationArr) {
            sum = sum.plus(parseStrDuration(strDuration));
        }

        System.out.println(formatDurationJava8Plus(sum));
        System.out.println(formatDurationJava9Plus(sum));
    }

    static Duration parseStrDuration(String strDuration) {
        String[] arr = strDuration.split(":");
        String strIsoDuration = "PT" + arr[0] + "H" + arr[1] + "M" + arr[2] + "S";
        return Duration.parse(strIsoDuration);
    }

    static String formatDurationJava8Plus(Duration duration) {
        return String.format("%d:%02d:%02d", duration.toHours(), duration.toMinutes() % 60, duration.toSeconds() % 60);

    }

    static String formatDurationJava9Plus(Duration duration) {
        return String.format("%d:%02d:%02d", duration.toHours(), duration.toMinutesPart(), duration.toSecondsPart());
    }
}

Output:

198:00:00
198:00:00

ONLINE DEMO

Learn more about the modern Date-Time API from Trail: Date Time.


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Upvotes: 3

pedagogyfirst
pedagogyfirst

Reputation: 53

I didn't test it but I'm pretty sure it's something like this:

     private static String sumTime(String t1, String t2){
        byte extraMinutes=0;
        byte extraHours=0;

        String arrt1[] = t1.split(":");
        String arrt2[] = t2.split(":");

        int seconds = Integer.valueOf(arrt1[2]) + Integer.valueOf(arrt2[2]);
        if(seconds>=60) {
            extraMinutes = 1;
            seconds = seconds % 60;
        }
        int minutes = Integer.valueOf(arrt1[1]) + Integer.valueOf(arrt2[1]) + extraMinutes;
        if(minutes>=60){
            extraHours = 1;
            minutes = minutes % 60;
        }
        int hours = Integer.valueOf(arrt1[0])  + Integer.valueOf(arrt2[0]) + extraHours;
        if(hours>=24) hours = hours%24;

        return hours+":"+minutes+":"+seconds;
    }

Upvotes: 0

Abhishek
Abhishek

Reputation: 2525

I have intentionally left the println so that you can see the code flow. hope this helps you...

public static void main(String[] args) {
        String time[] = { "160:00:00", "24:00:00", "13:50:00", "00:10:00" };
        int hours = 0, minutes = 0, seconds = 0;
        for (String string : time) {
            String temp[] = string.split(":");
            hours = hours + Integer.valueOf(temp[0]);
            minutes = minutes + Integer.valueOf(temp[1]);
            seconds = seconds + Integer.valueOf(temp[2]);
        }
        System.out.println(hours + ":" + minutes + ":" + seconds);
        if (seconds == 60) {
            minutes = minutes + 1;
            seconds = 0;
        } else if (seconds > 59) {
            minutes = minutes + (seconds / 60);
            seconds = seconds % 60;
        }
        System.out.println(hours + ":" + minutes + ":" + seconds);
        if (minutes == 60) {
            hours = hours + 1;
            minutes = 0;
        } else if (minutes > 59) {
            hours = hours + (minutes / 60);
            minutes = minutes % 60;
        }
        System.out.println(hours + ":" + minutes + ":" + seconds);
        String output = "";
        output = String.valueOf(hours);
        output = output.concat(":" + (String.valueOf(minutes).length() == 1 ? "0" + String.valueOf(minutes) : String.valueOf(minutes)));
        output = output.concat(":" + (String.valueOf(seconds).length() == 1 ? "0" + String.valueOf(seconds) : String.valueOf(seconds)));
        System.out.println(output);
}

Upvotes: 0

Related Questions