Search code examples
androidtimedurationseconds

Android : how can I add 5 Times in a variable and get total seconds of them


like i have 5 Times

1. 05:12:02
2. 19:12:52
3. 40:12:14
4. 56:54:10
5. 41:12:12
-----------
Total Seconds : 0#####..`
-----------

i want like this, how can i , please help me .

can I use this? :

 public String addTime(int hour, int minute, int minutesToAdd) {
    Calendar calendar = new GregorianCalendar(1990, 1, 1, hour, minute);
    calendar.add(Calendar.MINUTE, minutesToAdd);
    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
    String date = sdf.format(calendar.getTime());
    return date;
}

Solution

  • A easy way to do it, if the format is the one you have pointed, without have to worry in convert the Date is the following:

    int totalSum = getSecondsFromDate("05:12:02") + getSecondsFromDate("19:12:52") + getSecondsFromDate("40:12:14") + getSecondsFromDate("56:54:10") + getSecondsFromDate("41:12:12");
    
    private int getSecondsFromDate(String date){
      //We split the date to have hours, minutes and seconds
      String splitDate = date.split(":");
      int hours = Integer.parseInt(splitDate[0]);
      int minutes = Integer.parseInt(splitDate[1]);
      int seconds = Integer.parseInt(splitDate[2]);
    
      int totalSeconds = (hours*60*60) + (minutes*60) + seconds;
      return totalSeconds;
    }