有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java计算24小时时钟的平均时间(hh:mm:ss)

我的时间是23:00:00,1:00:00。所以平均时间应该是00:00:00。我正在用Java做这件事。但我不明白其中的逻辑

我已经转到了这个链接 “Find average of time in (hh mm ss) format in java” 它显示乘以60,但如果时间在23:00:00和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);}

共 (2) 个答案

  1. # 1 楼答案

    下面是使用LocalTimeDuration的解决方案

    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);
    }
    

    错误处理不存在,所以我假设输入字符串包含两个格式正确的时间值

  2. # 2 楼答案

    考虑到时间是按时间顺序排列的,所以在“23:00:00 1:00:00”中,1:00:00表示第二天的凌晨1点,您可以使用以下CalculateArgeOftime方法

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