gpt4 book ai didi

java - 计算平均时间(hh :mm:ss) of a 24 hour clock

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:30:50 24 4
gpt4 key购买 nike

我在 HHMMSS 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);}

最佳答案

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

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

关于java - 计算平均时间(hh :mm:ss) of a 24 hour clock,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56287060/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com