Why javax.xml.datatype.Duration.getMinutes() always returns 0 although the duration is incremented? If you run the code below longer than a minute you will see the output like this:
minutes: 0 , seconds: 61
I have never used this class before. Do I miss some basic knowledge about it?
Here is the code:
import java.util.Timer;
import java.util.TimerTask;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.Duration;
public class TestDuration {
class MyTimerTask extends TimerTask {
DatatypeFactory df;
long delay;
Duration duration;
public MyTimerTask(DatatypeFactory df, long delay) {
this.df = df;
this.delay = delay;
duration = df.newDuration(0);
}
@Override
public void run() {
duration = duration.add(df.newDuration(delay));
System.out.println("minutes: " + duration.getMinutes() + " , seconds: " + duration.getSeconds());
}
}
public static void main(String[] args) {
Timer timer = new Timer();
final long delay = 1 * 1000;
DatatypeFactory df = null;
try {
df = DatatypeFactory.newInstance();
} catch (DatatypeConfigurationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
MyTimerTask task = new TestDuration().new MyTimerTask(df, delay);
timer.schedule(task, 0, delay);
}
}
This is by design it seems. Take a look at the JavaDoc for Duration.add():
I’ve emboldened the line that matters here. Clearly this class is only concerned with correctly representing the interval, rather than worrying about what makes sense from a "human" perspective.
Depending upon your use case, you can either continue to work with
Duration, but understand that you will need to perform formatting calculations before displaying the value to a user, or you should move to a different class that does what you expect when you perform addition/subtraction. An example might be theDurationandPeriodclasses from the Yoda Time project.