我想计算两个XmlGregorianCalendar
个对象之间的时间增量,一个减法,以便创建一个Duration
对象。
但我还没有找到干净的方法来进行减法。你会怎么做?
答案 0 :(得分:12)
应该是:
DatatypeFactory.newDuration(xgc2.toGregorianCalendar().getTimeInMillis() - xgc1.toGregorianCalendar().getTimeInMillis())
答案 1 :(得分:1)
可接受的答案仅以毫秒分辨率给出结果,但是XmlGregorianCalendar允许无限精度。我们必须解决µS分辨率的问题。我通过转换为大十进制并使用getFractionalSeconds做到了这一点。见下文
public static BigDecimal convertXMLGregorianToSecondsAndFractionalSeconds(XMLGregorianCalendar xgc){
long ms = xgc.toGregorianCalendar().getTimeInMillis();
long secs = ms / 1000l;
BigDecimal decValue = BigDecimal.valueOf(secs);
BigDecimal fracSects = xgc.getFractionalSecond();
decValue = decValue.add(fracSects);
return decValue;
}
@Test
public void testSubtraction() throws Exception {
XMLGregorianCalendar xgc1 = DatatypeFactory.newInstance().newXMLGregorianCalendar("2015-05-22T16:28:40.317123-04:00");
XMLGregorianCalendar xgc2 = DatatypeFactory.newInstance().newXMLGregorianCalendar("2015-05-22T16:28:40.917124-04:00");
BigDecimal bd1 = MathUtils.convertXMLGregorianToSecondsAndFractionalSeconds(xgc1);
BigDecimal bd2 = MathUtils.convertXMLGregorianToSecondsAndFractionalSeconds(xgc2);
BigDecimal result = bd2.subtract(bd1);
Assert.assertTrue(result.equals(new BigDecimal("0.600001")));
}