如何解析dHHmm到持续时间?

时间:2015-02-05 14:27:50

标签: java jodatime

我有一个格式为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

1 个答案:

答案 0 :(得分:0)

首先,您希望从org.joda.time.Duration ...

获取dHHmm
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();
}