如何将 dHHmm 解析为持续时间?

How to parse dHHmm to Duration?

我有一个格式为 dHHmm 的字符串,代表一段时间,我想得到等效的 minutes.

因此我试图将其转换为 org.joda.time.Duration.getMinutes() 对象。但是似乎没有一种 DurationParser 可以用于此。

我怎样才能最好地转换这个字符串?

这是我尝试过的方法,但没有用:

PeriodFormatter formatter = new PeriodFormatterBuilder()
    .appendDays()
    .appendHours()
    .appendMinutes()
    .toFormatter();

assertTrue(formatter.parsePeriod("00310").getMinutes == 190); //failed with =0

所以,首先你想从 dHHmm...

得到 org.joda.time.Duration
import org.joda.time.Duration;

public Duration fromTheFormat( String str ) {
    Duration dayDuration = Duration.standardDays( parseInt( str.substring( 0, 1 ) ) );
    Duration hourDuration = Duration.standardHours( parseInt( str.substring( 1, 3 ) ) );
    Duration minuteDuration = Duration.standardMinutes( parseInt( str.substring( 3, 5 ) ) );

    return dayDuration.plus( hourDuration.getMillis() ).plus( minuteDuration.millis() );
}

import org.joda.time.Duration;
import org.joda.time.Period;
import org.joda.time.format.PeriodFormatter;

public Duration fromTheFormat( String str ) {
    Period period = new Period( /* years = */ 0,
                                /* months = */ 0,
                                /* weeks = */ 0,
                                /* days = */ parseInt( str.substring( 0, 1 ) ),
                                /* hours = */ parseInt( str.substring( 1, 3 ) ),
                                /* minutes = */ parseInt( str.substring( 3, 5 ),
                                /* seconds = */ 0,
                                /* millis = */ 0
    );

    // or best one is
    PeriodFormatter pf = new PeriodFormatterBuilder()
                           .minimumPrintedDigits( 1 )
                           .maximumParsedDigits( 1 )
                           .appendDays()
                           .minimumPrintedDigits( 2 )
                           .maximumParsedDigits( 2 )
                           .appendHours()
                           .appendMinutes()
                           .toFormatter();

    period = pf.parsePeriod( str );

    return period.toStandardDuration();
}