quma
quma

Reputation: 5743

JodaTime - hours and minutes

I will calculate the hours and minutes of different intervals. My approach is to have durations and add one another duration to the existing one. My question now would be how I can at least convert the duration into hours and time so that the result is e.g. 43:34 (43 hours and 34 minutes)

Thanks a lot!

@Test
public void shouldCalculateHoursOfWeekAverage() throws BusinessException {
    final DateTime start1 = formatter.parseDateTime("02.10.2015 07:20");
    final DateTime end1 = formatter.parseDateTime("02.10.2015 12:00");

    final DateTime start2 = formatter.parseDateTime("02.10.2015 08:00");
    final DateTime end2 = formatter.parseDateTime("02.10.2015 12:00");

    final Duration duration1 = new Interval(start1, end1).toDuration();

    final Duration duration2 = duration1.withDurationAdded(new Interval(start2, end2).toDuration(), 1);

    System.out.println("duration2: " + duration2 + ", --> " + duration2.getStandardHours() + ":" + duration2.getStandardMinutes());
}

[EDIT]

I have e.g. this Intervals (dates do not have any relevance, only time is in focus):

08:30-12:00
14:00-17:00
13:00-18:00

I will it sum up and the result should be in this case: 11:30

Upvotes: 0

Views: 2330

Answers (1)

Adam Michalik
Adam Michalik

Reputation: 9955

See the Duration JavaDoc:

A duration may be converted to a Period to obtain field values. This conversion will typically cause a loss of precision.

So to extend your test case:

@Test
public void shouldCalculateHoursOfWeekAverage() {
    DateTimeFormatter formatter = DateTimeFormat.forPattern("dd.MM.yyyy HH:mm");
    DateTime start1 = formatter.parseDateTime("02.10.2015 07:20");
    DateTime end1 = formatter.parseDateTime("02.10.2015 12:00");

    DateTime start2 = formatter.parseDateTime("02.10.2015 08:00");
    DateTime end2 = formatter.parseDateTime("02.10.2015 12:00");

    Duration duration1 = new Interval(start1, end1).toDuration();

    Duration duration2 = duration1.withDurationAdded(new Interval(start2, end2).toDuration(), 1);

    System.out.println("duration2: " + duration2 + ", --> " + duration2.getStandardHours() + ":" + duration2.getStandardMinutes());

    // Convert to Period
    Period period = duration2.toPeriod();
    System.out.println("Period: " + period + ", --> " + period.getHours() + ":" + period.getMinutes());
}

prints

duration2: PT31200S, --> 8:520
Period: PT8H40M, --> 8:40

and the total duration/period is indeed 8 h 40 min. So you either might convert your Durations to Periods or just work with Periods, depending on your use case.

Upvotes: 0

Related Questions