views:

39

answers:

1

I have a JodaTime Period that I've created from two DateTime instants. Is there a good way to convert that Period into a decimal number of hours?

For instance, I have a Period that goes from 1pm to 1:30pm on Jan 1, 2010. How can I get that Period as 1.5 hours.

In the past I've manually converted using seconds and BigDecimals such as this:

int seconds = myPeriod.toStandardSeconds().getSeconds();
BigDecimal d = new BigDecimal((double) seconds / 3600);
// Round to two decimals
BigDecimal correctResult = d.setScale(2, RoundingMode.HALF_DOWN);

This kind of feels like a hack, not to mention awkward when I start adding Periods together. It seems like there should be a better way.

Any ideas? Thanks

+2  A: 

If you've got two DateTimes, I'd expect you to have a Duration between them rather than a Period... but other than that and Mike's comments, that looks correct:

private static final BigDecimal SECONDS_PER_HOUR = 
    BigDecimal.valueOf(DateTimeConstants.SECONDS_PER_HOUR);
...
DateTime dt1 = ...;
DateTime dt2 = ...;
Duration duration = new Duration(dt1, dt2);
BigDecimal result = BigDecimal.valueOf(duration.toStandardSeconds().getSeconds())
                              .divide(SECONDS_PER_HOUR)
                              .setScale(2, RoundingMode.HALF_DOWN);

Note that you can avoid the toStandardSeconds().getSeconds() using Duration.getMillis() instead:

private static final BigDecimal MILLIS_PER_HOUR = 
    BigDecimal.valueOf(DateTimeConstants.MILLIS_PER_HOUR);
...
DateTime dt1 = ...;
DateTime dt2 = ...;
Duration duration = new Duration(dt1, dt2);
BigDecimal result = BigDecimal.valueOf(duration.getMillis())
                              .divide(MILLIS_PER_HOUR)
                              .setScale(2, RoundingMode.HALF_DOWN);
Jon Skeet