calculate average of time(hh:mm:ss) of a 24 hour clock

Ashutosh Soni :

I have time in HHMMSS 23:00:00, 1:00:00. So the average of time should be 00:00:00. I am doing this in Java. But I can't get the logic

I have gone to this link 'Find average of time in (hh mm ss) format in java' which showed multiply by 60, but this will not work if the time is after 23:00:00 and 1:00:00.

public static String calculateAverageOfTime(String timeInHHmmss) {
String[] split = timeInHHmmss.split(" ");
long seconds = 0;
for (String timestr : split) {
    String[] hhmmss = timestr.split(":");
    seconds += Integer.valueOf(hhmmss[0]) * 60 * 60;
    seconds += Integer.valueOf(hhmmss[1]) * 60;
    seconds += Integer.valueOf(hhmmss[2]);
}
seconds /= split.length;
long hh = seconds / 60 / 60;
long mm = (seconds / 60) % 60;
long ss = seconds % 60;
return String.format("%02d:%02d:%02d", hh,mm,ss);}
Joakim Danielson :

Here is solution that uses LocalTime and Duration

static LocalTime stringToTime(String str) {
    String[] components = str.split(":");
    return  LocalTime.of( Integer.valueOf(components[0]), Integer.valueOf(components[1]), Integer.valueOf(components[2]));
}

public static String calculateAverageOfTime(String timeInHHmmss) {
  String[] timesArray = timeInHHmmss.split(" ");

  LocalTime startTime = stringToTime(timesArray[0]);
  LocalTime endTime = stringToTime(timesArray[1]);

  Duration duration = Duration.between(startTime, endTime);
  if (startTime.isAfter(endTime)) {
    duration = duration.plusHours(24);
  }

  LocalTime average = startTime.plus(duration.dividedBy(2L));
  DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH:mm:ss");

  return average.format(dtf);
}

Error handling is non existent so I assume the input string contains two correctly formatted time values

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=99381&siteId=1