Domanda

Ho creato un metodo che accetta due date (in millisecondi) e restituisce una frase che indica la durata tra queste due date.

Per il momento, ho questo codice:

public static String formatDuration(long start, long end) {
    Interval interval = new Interval(start, end);
    return getPeriodFormatter().print(interval.toPeriod()).trim();
}

private static PeriodFormatter getPeriodFormatter() {
    PeriodFormatter pf = new PeriodFormatterBuilder().printZeroRarelyFirst()
        .appendYears().appendSuffix("y ", "y ")
        .appendMonths().appendSuffix("m" , "m ")
        .appendDays().appendSuffix("d ", "d ")
        .appendHours().appendSuffix("h ", "h ")
        .appendMinutes().appendSuffix("m ", "m ")
        .appendSeconds().appendSuffix("s ", "s ")
        .toFormatter();

    return pf;
}

Comunque, credo di fraintendere il modo in cui devo definire un intervallo in JodaTime. Se provo il seguente codice di prova:

@Test
public void foobar() {
    try {
        TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss dd/MM/yyyy");
        long start = sdf.parse("10:30:00 24/06/2009").getTime();
        long end = sdf.parse("23:05:17 22/08/2009").getTime();
        System.out.println("Duration: " + formatDuration(start, end));
    } catch (Exception e) {
        e.printStackTrace();
        fail("Could not test duration.");
    }
}

ottengo il seguente output, che è sbagliato (soprattutto da parte giorno):

Duration: 1m 1d 12h 35m 17s

Come faccio a definire la durata corretta JodaTime?


Ok, in realtà, ciò che ho dimenticato nella mia PeriodFormatter è quello di aggiungere le settimane. Quindi, se aggiungo le settimane, ottengo l'uscita seguente, che è corretto:

Duration: 1m 4w 1d 12h 35m 17s

Quindi la mia domanda cambia un po ': Esiste un modo per visualizzare il numero di giorni nel mese, invece di settimane + giorni? In parole degli altri, invece di avere:

Duration: 1m 4w 1d 12h 35m 17s

Io voglio avere:

Duration: 1m 29d 12h 35m 17s
È stato utile?

Soluzione

Prova questo.

    Period period = interval.toPeriod( PeriodType.yearMonthDayTime() );

Prima di formattare il periodo.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top