2

This is my first oportunity to play with the "new" java.time package from Java 8.

I need to get the total elapsed time, something like:
1 day, 2h:3m:4s 5ms

I know that have 2 TemporalAmount implementations for intervals:
- Period for years, months and days
- Duration for hours, minutes, seconds, milliseconds and nanoseconds

There's a way to mix these two or something more straightforward than "do math"?

That was the best I could do until now: (Updated with a new improved version)

LocalDateTime start = LocalDateTime.now();
// Forcing a long time execution to measure
LocalDateTime end = start
        .plusDays(1)
        .plusHours(2)
        .plusMinutes(3)
        .plusSeconds(4)
        .plusNanos(5000);

LocalDateTime elapsed = end
        .minusDays(start.getDayOfYear())
        .minusHours(start.getHour())
        .minusMinutes(start.getMinute())
        .minusSeconds(start.getSecond())
        .minusNanos(start.getNano());

Period period = Period.between(start.toLocalDate(), end.toLocalDate());
long days = period.getDays();

long hours = elapsed.getHour();
long minutes = elapsed.getMinute();
long seconds = elapsed.getSecond();
long milliseconds = elapsed.getNano() / 1000;

StringBuilder msg = new StringBuilder();
msg.append(seconds);
msg.append("s ");
msg.append(milliseconds);
msg.append("ms");
if(minutes > 0) {
    msg.insert(0, "m:");
    msg.insert(0, minutes);
}
if(hours > 0) {
    msg.insert(0, "h:");
    msg.insert(0, hours);
}
if(days > 0) {
    msg.insert(0, days == 1 ? " day, " : " days, ");                
    msg.insert(0, days);
}

System.out.println(msg.toString());

Thanks for your time =)

assylias
  • 321,522
  • 82
  • 660
  • 783
Eric Sant'Anna
  • 267
  • 4
  • 17

1 Answers1

3

Seems like you need the PeriodFormatter from JodaTime. See below links:

How to format a duration in java? (e.g format H:MM:SS)

Formatting a Duration in Java 8 / jsr310

Given these two, I suggest using JodaTime for Duration.

Community
  • 1
  • 1
John B
  • 32,493
  • 6
  • 77
  • 98
  • Thanks, I already knew about JodaTime, but I don't want one more dependency in my project only to do this once in the whole code. Anyway, the second link answers my question: there's no JodaTime's `PeriodType` equivalent in Java Time API. – Eric Sant'Anna Aug 07 '14 at 15:59