将小时和分钟相加 Java

huangapple go评论63阅读模式
英文:

Sum hours and minutes together Java

问题

Summing hours and minutes together results in the wrong answer.

Here are 2 lists with hours.

[[0小时:0分钟:0秒,1小时:16分钟:22秒,0小时:1分钟:53秒,23小时:54分钟:18秒],[0小时:8分钟:22秒,0小时:8分钟:22秒,0小时:8分钟:22秒]]这是小时

Then, I divide it into sublists, to calculate for each. Here is one of the sublists.

[0小时:0分钟:0秒,1小时:16分钟:22秒,0小时:1分钟:53秒,23小时:54分钟:18秒]

So, the answer I get for this sublist is: 1小时12分钟33秒,which is incorrect. I suppose to get around 25小时加上几分钟。

public List<String> getTheHoursWorked() {
    DateTimeFormatter parser = DateTimeFormatter.ofPattern("H 'hours :' m 'mins :' s 'sec'", Locale.US);
    final DateFormat dt = new SimpleDateFormat("HH:mm:ss");
    final Calendar c = Calendar.getInstance(TimeZone.getDefault(), Locale.getDefault());

    c.clear();
    long startingMS = c.getTimeInMillis();
    int counter = 0;

    for (int k = 0; k < hours.size(); k++) {
        List<Object> shorter = new ArrayList<>();
        List<Object> temp;
        temp = (List<Object>) hours.get(k);

        long milliseconds = 0;
        for (int m = 0; m < shorter.size(); m++) {
            LocalTime odt = LocalTime.parse((CharSequence) shorter.get(m), parser);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
            String printDate = formatter.format(odt);
            try {
                milliseconds = milliseconds + (dt.parse(printDate).getTime() - startingMS);
                System.out.println(milliseconds + "MILISECONDS");
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        hoursToString.add(String.valueOf(shorter));
        String s = milliseconds / 1000 % 60 + " seconds";
        String m = milliseconds / (60 * 1000) % 60 + " minutes";
        String h = milliseconds / (60 * 60 * 1000) % 24 + " hours";
        String together = h + ":" + m + ":" + s;
        togetherHours.add(together);
    }
    return togetherHours;
}
英文:

Summing hours and minutes together results in the wrong answer.

Here are 2 lists with hours.

[[0 hours : 0 mins : 0 sec, 1 hours : 16 mins : 22 sec, 0 hours : 1 mins : 53 sec, 23 hours : 54 mins : 18 sec], [0 hours : 8 mins : 22 sec, 0 hours : 8 mins : 22 sec, 0 hours : 8 mins : 22 sec]]this is HOURS

Then, I divide it into sublists, to calculate for each. Here is one of the sublists.

[0 hours : 0 mins : 0 sec, 1 hours : 16 mins : 22 sec, 0 hours : 1 mins : 53 sec, 23 hours : 54 mins : 18 sec]

So, the answer I get for this sublist is: 1 hours:12 minutes:33 seconds, which is incorrect. I suppose to get around 25 hours plus a few minutes.

public List&lt;String&gt; getTheHoursWorked() {
DateTimeFormatter parser = DateTimeFormatter.ofPattern(&quot;H &#39;hours :&#39; m &#39;mins :&#39; s &#39;sec&#39;&quot;, Locale.US);
final DateFormat dt = new SimpleDateFormat(&quot;HH:mm:ss&quot;);
final Calendar c = Calendar.getInstance(TimeZone.getDefault(), Locale.getDefault());
c.clear();
long startingMS = c.getTimeInMillis();
int counter = 0;
for (int k = 0; k &lt; hours.size(); k++){
List&lt;Object&gt; shorter = new ArrayList&lt;&gt;();
List&lt;Object&gt; temp;
temp = (List&lt;Object&gt;) hours.get(k);
long milliseconds = 0;
for (int m = 0; m &lt; shorter.size(); m++) {
LocalTime odt = LocalTime.parse((CharSequence) shorter.get(m), parser);
DateTimeFormatter formatter =
DateTimeFormatter.ofPattern(&quot;HH:mm:ss&quot;);
String printDate = formatter.format(odt);
try {
milliseconds = milliseconds + (dt.parse(printDate).getTime() - startingMS);
System.out.println(milliseconds + &quot;MILISECONDS&quot;);
} catch (ParseException e) {
e.printStackTrace();
}
}
hoursToString.add(String.valueOf(shorter));
String s = milliseconds / 1000 % 60   + &quot; seconds&quot;;
String m = milliseconds /(60 * 1000) % 60 + &quot; minutes&quot;;
String h = milliseconds / (60 * 60 * 1000) % 24 + &quot; hours&quot;;
String together = h+&quot;:&quot;+m+&quot;:&quot;+s;
togetherHours.add(together);
}
return togetherHours;
}

答案1

得分: 3

代码部分不提供翻译。以下为您提供的内容翻译:

解决方案的步骤应为:

  1. 从时间 0:0 开始。
  2. 遍历列表,在解析时间字符串并使用相应的格式化程序进行解析后,分别添加所有小时、分钟和秒数。
  3. 如果分钟和/或秒数超过 60,则调整小时、分钟和秒数。

演示:

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> list = List.of("0 hours : 0 mins : 0 sec", "1 hours : 16 mins : 22 sec",
"0 hours : 1 mins : 53 sec", "23 hours : 54 mins : 18 sec");
// 从时间 0:0 开始
int sumHours = 0;
int sumMinutes = 0;
int sumSeconds = 0;
// 遍历列表,在解析时间字符串并使用相应的格式化程序进行解析后,分别添加所有小时、分钟和秒数
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("H' hours : 'm' mins : 's' sec'");
for (String strTime : list) {
LocalTime time = LocalTime.parse(strTime, timeFormatter);
sumHours += time.getHour();
sumMinutes += time.getMinute();
sumSeconds += time.getSecond();
}
// 如果分钟和/或秒数超过 60,则调整小时、分钟和秒数
sumMinutes += sumSeconds / 60;
sumSeconds %= 60;
sumHours += sumMinutes / 60;
sumMinutes %= 60;
String strSum = String.format("%d hours : %d mins : %d sec", sumHours, sumMinutes, sumSeconds);
System.out.println(strSum);
}
}

输出:

25 hours : 12 mins : 33 sec
英文:

The steps of the solution should be

  1. Start with a time of 0:0
  2. Iterate the list and add all hours, minutes and seconds separately after parsing the time strings using the corresponding formatter.
  3. Adjust hour, minutes and seconds if minute and/or second exceed 60.

Demo:

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
public class Main {
public static void main(String[] args) {
List&lt;String&gt; list = List.of(&quot;0 hours : 0 mins : 0 sec&quot;, &quot;1 hours : 16 mins : 22 sec&quot;,
&quot;0 hours : 1 mins : 53 sec&quot;, &quot;23 hours : 54 mins : 18 sec&quot;);
// Start with a time of 0:0
int sumHours = 0;
int sumMinutes = 0;
int sumSeconds = 0;
// Iterate the list and add all hours, minutes and seconds separately after
// parsing the time strings using the corresponding formatter
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern(&quot;H&#39; hours : &#39;m&#39; mins : &#39;s&#39; sec&#39;&quot;);
for (String strTime : list) {
LocalTime time = LocalTime.parse(strTime, timeFormatter);
sumHours += time.getHour();
sumMinutes += time.getMinute();
sumSeconds += time.getSecond();
}
// Adjust hour, minutes and seconds if minute and/or second exceed 60
sumMinutes += sumSeconds / 60;
sumSeconds %= 60;
sumHours += sumMinutes / 60;
sumMinutes %= 60;
String strSum = String.format(&quot;%d hours : %d mins : %d sec&quot;, sumHours, sumMinutes, sumSeconds);
System.out.println(strSum);
}
}

Output:

25 hours : 12 mins : 33 sec

答案2

得分: 2

一种处理方法是使用 Duration。将每个时间值转换为持续时间,然后将它们求和。提供的时间值显示在包含两个字符串的数组中。

String[] hours = {
    "0 hours : 0 mins : 0 sec, 1 hours : 16 mins : 22 sec, 0 hours : 1 mins : 53"
            + "sec, 23 hours : 54 mins : 18 sec",
    "0 hours : 8 mins : 22 sec, 0 hours : 8"
            + " mins : 22 sec, 0 hours : 8 mins : 22 sec" };

使用流进行转换。该过程在注释中有解释。

List<Duration> times = Arrays.stream(hours)
    // 去除每个字符串中的所有空格
    .map(str -> str.replaceAll("\\s+", ""))

    // 在逗号上拆分每个字符串。此时,每个字符串都是独立处理的,
    // 在单独的流中进行处理
    .map(str -> Arrays.stream(str.split(","))

        // 解析时间
        .map(tm -> LocalTime.parse(tm,
                DateTimeFormatter.ofPattern(
                        "H'hours':m'mins':s'sec'")))

        // 将每个时间转换为持续时间
        .map(lt -> Duration
                .between(LocalTime.of(0, 0, 0), lt))

        // 求持续时间之和
        .reduce(Duration.ZERO, (a, b) -> a.plus(b)))
    // 并收集到列表中
    .collect(Collectors.toList());

此时,您可以以标准的持续时间格式打印持续时间。

times.forEach(System.out::println);

打印结果

PT25H12M33S
PT25M6S

要以更熟悉的格式打印它们,可以使用以下 lambda 表达式。

Function<Duration, String> durationToString = d -> {
    StringBuilder timeString = new StringBuilder();   
    long h = d.toDaysPart()*24+d.toHoursPart();
    timeString.append(h == 1 ? (h + " hour ") : h > 1 ?  (h + " hours ") : "");
    long m = d.toMinutesPart();
    timeString.append(m == 1 ? (m + " minute ") : m > 1 ? (m + " minutes ") : "");
    long s = d.toSecondsPart();
    timeString.append(s == 1 ? (s + " second ") : s > 1 ? (s + " seconds ") : "");
    return timeString.toString();
};

打印结果

25 hours 12 minutes 33 seconds 
25 minutes 6 seconds 
英文:

One way to approach this is to use Duration. Convert each time value to a duration and then sum them. The supplied time values are shown in an array of two strings.

String[] hours = {
&quot;0 hours : 0 mins : 0 sec, 1 hours : 16 mins : 22 sec, 0 hours : 1 mins : 53&quot;
+ &quot;sec, 23 hours : 54 mins : 18 sec&quot;,
&quot;0 hours : 8 mins : 22 sec, 0 hours : 8&quot;
+ &quot; mins : 22 sec, 0 hours : 8 mins : 22 sec&quot; };

The conversion is done using streams. The process is explained in the comments.

List&lt;Duration&gt; times = Arrays.stream(hours)
// remove all the spaces in each string
.map(str -&gt; str.replaceAll(&quot;\\s+&quot;, &quot;&quot;))
// split each string on the commas.  At this
// point, each string is processed independently
// of the other in a separate stream
.map(str -&gt; Arrays.stream(str.split(&quot;,&quot;))
// parse the time
.map(tm -&gt; LocalTime.parse(tm,
DateTimeFormatter.ofPattern(
&quot;H&#39;hours&#39;:m&#39;mins&#39;:s&#39;sec&#39;&quot;)))
// convert each time to a duration
.map(lt -&gt; Duration
.between(LocalTime.of(0, 0, 0), lt))
// sum the durations
.reduce(Duration.ZERO, (a, b) -&gt; a.plus(b)))
// and collect in a list
.collect(Collectors.toList());

At this point you can print the durations in the standard Duration format.

times.forEach(System.out::println);

Prints

PT25H12M33S
PT25M6S

To print them in a more familiar format, the following lambda can be used.

Function&lt;Duration, String&gt; durationToString = d -&gt; {
StringBuilder timeString = new StringBuilder();   
long h = d.toDaysPart()*24+d.toHoursPart();
timeString.append(h == 1 ? (h + &quot; hour &quot;) : h &gt; 1 ?  (h + &quot; hours &quot;) : &quot;&quot;);
long m = d.toMinutesPart();
timeString.append(m == 1 ? (m + &quot; minute &quot;) : m &gt; 1 ? (m + &quot; minutes &quot;) : &quot;&quot;);
long s = d.toSecondsPart();
timeString.append(s == 1 ? (s + &quot; second &quot;) : s &gt; 1 ? (s + &quot; seconds &quot;) : &quot;&quot;);
return timeString.toString();
};

Prints

25 hours 12 minutes 33 seconds 
25 minutes 6 seconds 
</details>
# 答案3
**得分**: 1
1) 你例程中的逻辑错误是 %24,所以你移除了整天。
2) 你的代码包含了许多无用的部分,比如 temp,并且不够清晰。
3) 在循环中构建解析器是一个非常糟糕的风格。
4) 你做了很多不必要的工作,使用毫秒和日历进行操作是没有意义的。这里有两个版本可以返回预期的结果。第二个版本适用于更新的 Java 版本。
```java
public static List<String> getTheHoursWorked() {
final DateTimeFormatter parser = DateTimeFormatter.ofPattern("H 'hours :' m 'mins :' s 'sec'", Locale.US);
final List<String> togetherHours = new LinkedList<>();
for (int k = 0; k < hours.size(); k++){
final List<String> shorter = hours.get(k);
long seconds = 0;
for (int m = 0; m < shorter.size(); m++) {
final LocalTime odt = LocalTime.parse(shorter.get(m), parser);
seconds += odt.getHour() * 3600 + odt.getMinute() * 60 + odt.getSecond();
}
final String s = (seconds       ) % 60 + " seconds";
final String m = (seconds /   60) % 60 + " minutes";
final String h = (seconds / 3600)      + " hours";
final String together = h+":"+m+":"+s;
togetherHours.add(together);
}
return togetherHours;
}
public static List<String> getTheHoursWorked_new() {
final DateTimeFormatter parser = DateTimeFormatter.ofPattern("H 'hours :' m 'mins :' s 'sec'", Locale.US);
final List<String> togetherHours = new LinkedList<>();
for (final var shorter: hours){
long seconds = 0;
for (final var duration : shorter) {
final LocalTime odt = LocalTime.parse(duration, parser);
seconds += odt.getHour() * 3600 + odt.getMinute() * 60 + odt.getSecond();
}
final String s = (seconds       ) % 60 + " seconds";
final String m = (seconds /   60) % 60 + " minutes";
final String h = (seconds / 3600)      + " hours";
final String together = h+":"+m+":"+s;
togetherHours.add(together);
}
return togetherHours;
}
英文:
  1. The logical error in your routine is %24 so you remove full days.

  2. Your code contain many useless parts like temp and is not clean.

  3. Building an parser in an loop is an very bad style.

  4. You do very much stuff that is not required and the working with milliseonds and calendar is useless. Here are two versions that return the expected result. Second is for newer java versions.

     public static List&lt;String&gt; getTheHoursWorked() {
    final DateTimeFormatter parser = DateTimeFormatter.ofPattern(&quot;H &#39;hours :&#39; m &#39;mins :&#39; s &#39;sec&#39;&quot;, Locale.US);
    final List&lt;String&gt; togetherHours = new LinkedList&lt;&gt;();
    for (int k = 0; k &lt; hours.size(); k++){
    final List&lt;String&gt; shorter = hours.get(k);
    long seconds = 0;
    for (int m = 0; m &lt; shorter.size(); m++) {
    final LocalTime odt = LocalTime.parse(shorter.get(m), parser);
    seconds += odt.getHour() * 3600 + odt.getMinute() * 60 + odt.getSecond();
    }
    final String s = (seconds       ) % 60 + &quot; seconds&quot;;
    final String m = (seconds /   60) % 60 + &quot; minutes&quot;;
    final String h = (seconds / 3600)      + &quot; hours&quot;;
    final String together = h+&quot;:&quot;+m+&quot;:&quot;+s;
    togetherHours.add(together);
    }
    return togetherHours;
    }
    public static List&lt;String&gt; getTheHoursWorked_new() {
    final DateTimeFormatter parser = DateTimeFormatter.ofPattern(&quot;H &#39;hours :&#39; m &#39;mins :&#39; s &#39;sec&#39;&quot;, Locale.US);
    final List&lt;String&gt; togetherHours = new LinkedList&lt;&gt;();
    for (final var shorter: hours){
    long seconds = 0;
    for (final var duration : shorter) {
    final LocalTime odt = LocalTime.parse(duration, parser);
    seconds += odt.getHour() * 3600 + odt.getMinute() * 60 + odt.getSecond();
    }
    final String s = (seconds       ) % 60 + &quot; seconds&quot;;
    final String m = (seconds /   60) % 60 + &quot; minutes&quot;;
    final String h = (seconds / 3600)      + &quot; hours&quot;;
    final String together = h+&quot;:&quot;+m+&quot;:&quot;+s;
    togetherHours.add(together);
    }
    return togetherHours;
    }
    

huangapple
  • 本文由 发表于 2020年10月21日 04:30:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/64452903.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定