Pergunta

say I have 110 seconds that I want to convert to 01:50 or 00:01:50 or such. How do I do that in joda-time? I load the number into Seconds but then toString is not doing the conversion for me.

Foi útil?

Solução

LocalTime time = new LocalTime(0, 0); // midnight
time = time.plusSeconds(110);
String output = DateTimeFormat.forPattern("HH:mm:ss").print(time);
System.out.println(output); // 00:01:50

Note this answer is valid for amounts of seconds less than one full day (86400). If you have bigger numbers then better use a formatter for durations (in Joda-Time called PeriodFormatter) - see also the right answer of @Isaksson.

Outras dicas

You can build a formatter for your format and use that. To get the time in seconds only normalized to minutes/seconds, use normalizedStandard();

PeriodFormatter myFormat =
    new PeriodFormatterBuilder()
        .printZeroAlways().minimumPrintedDigits(2).appendMinutes()
        .appendSeparator(":")
        .printZeroAlways().minimumPrintedDigits(2).appendSeconds()
        .toFormatter();

Period period = Period.seconds(110).normalizedStandard();
System.out.println(myFormat.print(period));

> 01:50
public static void main(String[] args) {
    Date dt = new Date();
    String date = String.format("%tH:%tM", dt, dt);
    System.out.println(date);
    // or System.out.printf("%tH:%tM", dt, dt);
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top