Search code examples
javadatetimeunit

CANCELED - TimeUnit.MINUTES.convert() method functionality


Well I'm trying to get diference between times and I'm using TimeUnit.XXX.convert().

Here's my piece of test code:

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");

        Date d1 = new Date();

        Date d2 = new Date();

try {
            d1 = sdf.parse("08/11/2015 10:00:00");
            d2 = sdf.parse("08/11/2015 14:30:00");
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        System.out.println("Duration in minutes: "  + TimeUnit.MINUTES.convert(d2.getTime()-d1.getTime(), TimeUnit.MILLISECONDS));
        System.out.println("Duration in hours: "    + TimeUnit.HOURS.convert(d2.getTime()-d1.getTime(), TimeUnit.MILLISECONDS));

The results were: 'Duration in minutes: 270' and 'Duration in hours: 4'.

enter image description here

But in fact the difference beteween 10:00:00 and 14:30:00 is 4,5 hours (decimal).

Is that a bug or am I doing something wrong?


Solution

  • 270 minutes if presented as hours are truncated to 4 hours.

    Remember that the method convert returns a long, not a decimal value.

    From javadoc

    Convert the given time duration in the given unit to this unit. Conversions from finer to coarser granularities truncate, so lose precision. For example converting 999 milliseconds to seconds results in 0.