javampxj

How Can I Calculate a Numerical Difference between 2 Durations in Java (Using mpxj Library)?


For example, I want to calculate the duration difference between 2 activities. Activity 1 has a 13 day duration. Activity 2 has a 5 day duration. I know Microsoft Project has difficulties doing operations with Durations. Thanks in advance!

Needed answer: 13-5 = 8 Ideal answer: 8 days


Solution

  • If your Durations both have the same time units, you can perform a simple subtraction:

    Duration d1 = Duration.getInstance(13, TimeUnit.DAYS);
    Duration d2 = Duration.getInstance(5, TimeUnit.DAYS);
    Duration result = Duration.getInstance(d1.getDuration() - d2.getDuration(), TimeUnit.DAYS);
    

    If you have different time units, you need to perform a conversion first:

    Duration d1 = Duration.getInstance(13, TimeUnit.DAYS);
    Duration d2 = Duration.getInstance(40, TimeUnit.HOURS);
    Duration d3 = d2.convertUnits(TimeUnit.DAYS, project.getProjectProperties());
    Duration result = Duration.getInstance(d1.getDuration() - d3.getDuration(), TimeUnit.DAYS);
    

    In the example above, the second duration is in hours (assuming 8 hours per working day), which we convert to days prior to calculating the difference. Note that we pass in the project properties to the convertUnits method. This provides the details of how many hours there are in a working day and so on to allow an accurate conversion. There are other variants of the convertUnits method which allow you to pass in these values yourself.