TimeUtil { static long deltaMs(long startMs, long endMs) { BigInteger startNs = BigInteger.valueOf(TimeUnit.NANOSECONDS. convert(startMs, TimeUnit.MILLISECONDS)); BigInteger endNs = BigInteger.valueOf(TimeUnit.NANOSECONDS. convert(endMs, TimeUnit.MILLISECONDS)); BigInteger deltaNs = endNs.subtract(startNs); if (deltaNs.signum() >= 0) { return TimeUnit.MILLISECONDS.convert(deltaNs.min( BigInteger.valueOf(Long.MAX_VALUE)).longValue(), TimeUnit.NANOSECONDS); } deltaNs = deltaNs.negate(); if (deltaNs.compareTo(BigInteger.valueOf(Long.MAX_VALUE / 2)) < 0) { return 0L; } BigInteger revDeltaNs = BigInteger.ONE.shiftLeft(64).subtract(deltaNs); return TimeUnit.MILLISECONDS.convert(revDeltaNs.min( BigInteger.valueOf(Long.MAX_VALUE)).longValue(), TimeUnit.NANOSECONDS); }    }
@Test(timeout = 60000) public void testDeltaMs() throws Exception { Assert.assertEquals(0, TimeUtil.deltaMs(0, 0)); Assert.assertEquals(1, TimeUtil.deltaMs(0, 1)); Assert.assertEquals(0, TimeUtil.deltaMs(1, 0)); Assert.assertEquals(10, TimeUtil.deltaMs(1000, 1010)); long minMs = TimeUnit.MILLISECONDS.convert(Long.MIN_VALUE, TimeUnit.NANOSECONDS); long maxMs = TimeUnit.MILLISECONDS.convert(Long.MAX_VALUE, TimeUnit.NANOSECONDS); Assert.assertEquals(10, TimeUtil.deltaMs(minMs, minMs + 10)); Assert.assertEquals(maxMs, TimeUtil.deltaMs(minMs, maxMs)); Assert.assertEquals(11, TimeUtil.deltaMs(maxMs - 10, minMs)); }