【问题标题】:Summing durations using Joda Time使用 Joda Time 对持续时间求和
【发布时间】:2015-02-10 01:29:10
【问题描述】:

我正在尝试以以下格式对持续时间求和:“hh:mm:ss”(例如:“08:55:12”)使用 Joda Time:

PeriodFormatter formatter = new PeriodFormatterBuilder()
    .printZeroAlways().minimumPrintedDigits(2).appendHours()
        .appendLiteral(":").printZeroAlways().printZeroAlways()
            .minimumPrintedDigits(2).appendMinutes().appendLiteral(":")
                .printZeroAlways().minimumPrintedDigits(2).appendSeconds()
                    .toFormatter();
Duration totalTime = Duration.ZERO;


for (Entry entry : entries) {
    Period period = formatter.parsePeriod(entry.getTime());
    Duration duration = period.toStandardDuration();
    totalTime = totalTime.plus(duration);
}

Period totalPeriod = totalTime.toPeriod();
if (totalPeriod.getHours() < 10) {
    hours = "0" + totalPeriod.getHours();
} else {
    hours = Integer.toString(totalPeriod.getHours());
}
mTextView.setTextView(hours
    + String.format("%02d:%02d", totalPeriod.getMinutes(),
        totalPeriod.getSeconds()));

由于某种原因,它给了我错误的结果(总持续时间太长了)。你能帮我找出这个问题的原因吗?

【问题讨论】:

  • 请给出一些示例输入、预期输出和实际输出。为我们提供一个可编译的自包含示例也将很有帮助(并且预期来自 2k+ 用户)。

标签: java android jodatime duration


【解决方案1】:

我认为您刚刚忘记了小时部分和分钟部分之间的冒号导致总和看起来像 2701:44 而不是 27:01:44(这是总和的示例Joda-Time正确计算的三个元素“03:20:45”、“00:40:11”、“23:00:48”)。

所以你的解决方案最终应该是这样的:

String output =
    hours + String.format(":%02d:%02d", totalPeriod.getMinutes(), totalPeriod.getSeconds());
System.out.println(output); // 27:01:44

但更简单的方法是重用格式化程序对象进行打印

System.out.println(formatter.print(totalPeriod)); // 27:01:44

如果您对基于模式的解决方案感兴趣,请查看我的库 Time4J 并使用以下示例:

// input
String[] periods = { "03:20:45", "00:40:11", "23:00:48" };

// initialization
Duration.Formatter<ClockUnit> timeFormat = 
    Duration.Formatter.ofPattern(ClockUnit.class, "hh:mm:ss");
Duration<ClockUnit> dur = Duration.ofZero();

// calculate the sum
for (String entry : periods) { 
    dur = dur.plus(timeFormat.parse(entry));
}

dur = dur.with(Duration.STD_CLOCK_PERIOD); // normalization
System.out.println(timeFormat.format(dur)); // 27:01:44

【讨论】:

    猜你喜欢
    • 2011-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多