如何将 java 中的 Period Class 的天数转换并追加到小时数?

How to convert and append days into hours of Period Class in java?

我有一个方法可以确定两个 dateTime 变量之间的周期。

Period period = new Period(startTime, endTime);
PeriodFormatter runDurationFormatter = new PeriodFormatterBuilder().printZeroAlways().minimumPrintedDigits(2).appendDays().appendSeparator(":").appendHours().appendSeparator(":").appendMinutes().appendSeparator(":").appendSeconds().toFormatter();
return runDurationFormatter.print(period);

我希望看到 00:01:00 1 分钟,23:00:00 23 小时,30:00:00 30 小时,120:00:00 120 小时(5 天) . 我尝试使用

Period daystoHours = period.normalizedStandard(PeriodType.time());

但 eclipse 显示 normalizedStandard() 方法未定义类型句点。

确保您使用的是 org.joda.time 包中的句点 class,而不是 java.time 中的。以下示例可能对您有所帮助。

import org.joda.time.Period;
import org.joda.time.PeriodType;
import org.joda.time.format.PeriodFormatter;
import org.joda.time.format.PeriodFormatterBuilder;

import java.util.Calendar;
import java.util.GregorianCalendar;

public class Launcher
{
    public static void main(String[] args)
    {
        Calendar start = new GregorianCalendar(2016, 4, 12, 0, 0, 0);
        Calendar end = new GregorianCalendar(2016, 4, 17, 0, 0, 0);

        Period period = new Period(start.getTimeInMillis(), end.getTimeInMillis());

        PeriodFormatter runDurationFormatter = new PeriodFormatterBuilder().printZeroAlways()
            .minimumPrintedDigits(2)
            .appendHours().appendSeparator(":")    // <-- say formatter to emit hours
            .appendMinutes().appendSeparator(":")  // <-- say formatter to emit minutes
            .appendSeconds()                       // <-- say formatter to emit seconds
            .toFormatter();

        // here we are expecting the following result string 120:00:00
        System.out.println(
            runDurationFormatter.print(period.normalizedStandard(PeriodType.time()))
        );
    }
}