android studio 中列表的持续时间总和

Sum of time duration's from a list in android studio

我正在尝试计算考勤应用程序持续时间列表的总和。我能够计算出 2 次的差异,但不确定如何遍历列表以将日期加在一起。

下面的代码是我到目前为止所尝试的。列表中有 2 个持续时间,它们是使用对象 class.

从 Firebase 添加到列表中的

持续时间 1 = 0:5:42
持续时间 2 = 0:0:09
预期总数 = 0:5:51

//初始化

long sum;

//当前尝试的方法

public void grandTotal() throws ParseException {
        java.util.Date date1;
        java.util.Date date2;

        DateFormat formatter = new SimpleDateFormat("hh:mm:ss");
        for(int i = 0 ; i < newList.size(); i++) {
            String str_time1 = newList.get(i).getDuration();
            date1 = formatter.parse(str_time1);

            for (int j = 1; j < newList.size(); j++) {
                String str_time2 = newList.get(j).getDuration();
                date2 = formatter.parse(str_time2);
                sum = date1.getTime() + date2.getTime();
            }
        }
        secs = sum/1000;

        mins = secs/60;
        secs%=60;
        hours = mins/60;
        mins%=60;
        txtDailyBalance.setText(hours+":"+mins+":"+String.format("%02d",secs));
    }

我得到的结果输出是=-1:59:42

我使用这种方法得到了解决方案,但我认为这不是一个好的做法,所以我一直在研究更多地了解此 post 中的不同方法,谢谢。

//Sum of time durations for that day
public void grandTotal() throws ParseException {
    java.util.Date date1;
    java.util.Date date2;

    DateFormat formatter = new SimpleDateFormat("hh:mm:ss");
    for(int i = 0 ; i < newList.size(); i++) {
        timeDuration.add(newList.get(i).getDuration());
    }
    long tDur = 0;
    for (String tmp : timeDuration){
        String[] arr = tmp.split(":");
        tDur += Integer.parseInt(arr[2]);
        tDur += 60 * Integer.parseInt(arr[1]);
        tDur += 3600 * Integer.parseInt(arr[0]);
    }
    long hours = tDur / 3600;
    tDur %= 3600;
    long mins = tDur / 60;
    tDur %= 60;
    long secs = tDur;
    txtDailyBalance.setText(hours+":"+mins+":"+String.format("%02d",secs));
}

正如我在评论中所说,使用 Duration class 持续时间:

    List<Duration> durations = List.of(
            Duration.ofMinutes(5).plusSeconds(42), // 0:05:42
            Duration.ofSeconds(9),                 // 0:00:09
            Duration.parse("PT11M"));              // 0:11:00

    Duration sum = Duration.ZERO;
    for (Duration dur : durations) {
        sum = sum.plus(dur);
    }

    System.out.println(sum);

这会打印

PT16M51S

所以 16 分 51 秒。

Durations 本机解析并生成 ISO 8601 格式,就像您刚刚看到的那样,PT16M51S。如果您需要 hh:mm:ss 格式的持续时间字符串,我相信您可以编写辅助方法来格式化和解析该格式。对于格式化,Stack Overflow 上已经有几个问题,例如 How to format a duration in java? (e.g format H:MM:SS)(搜索更多)。

为什么不 Date

使用 Date 持续时间是不正确的。时间点和时间量是两个不同的概念。您看到的错误可能是由于时区偏移造成的,但您在此过程中冒着其他错误的风险,更糟糕的是,您的代码难以阅读且容易被误解。

此外 Date class 早已过时并被 java.time 中的 class 取代,现代的 Java 日期和时间 API.同样的 API 引入了 classes Period(年、月和日)和 Duration(小时、分钟、秒和秒的小数部分)。

问题:我可以在 Android 上使用 java.time 吗?

是的,您可以在 Android 上使用 java.time。它只需要至少 Java 6.

  • 在 Java 8 及更高版本和更新的 Android 设备上,现代 API 是内置的。
  • 在 Java 6 和 7 中获取 ThreeTen Backport,新 classes 的 backport(ThreeTen 用于 JSR 310;请参阅底部的链接)。
  • 在较旧的 Android 上使用 ThreeTen Backport 的 Android 版本。它叫做 ThreeTenABP。并确保使用子包从 org.threeten.bp 导入日期和时间 classes。

链接

如果您不坚持使用自定义格式,而只是寻找一种更简单的方法来添加持续时间对象,那么 Oles 的答案可能适合您。但是,ThreetenABP 缺少持续时间格式化程序。

但是如果你想避免以 "hh:mm:ss" 格式编写用于格式化和解析持续时间的辅助方法(并且愿意添加第 3 方依赖项)那么你可以尝试我的库 Time4A and use a pattern-based 方法:

Duration.Formatter<ClockUnit> parser = Duration.formatter(ClockUnit.class, "#h:#m:ss");
String[] durations = { "0:5:42", "0:0:09" };
Duration<ClockUnit> d = Duration.ofZero();

for (String duration : durations) {
    d = d.plus(parser.parse(duration));
}

d = d.with(Duration.STD_CLOCK_PERIOD); // normalization
Duration.Formatter<ClockUnit> printer = Duration.formatter(ClockUnit.class, "hh:mm:ss");
System.out.println(printer.format(d)); // 00:05:51