我需要将一个Instant转换为.Net的DateTime.Ticks,也就是一个长整型,表示自01年1月1日0:00:00UTC以来的100纳秒数。
不幸的是,没有ChronoUnit.HUNDRED_NANOS这样的东西,所以似乎人们必须自己编写代码。
发布于 2018-02-28 09:22:25
下面的函数toDotNetDateTimeTicks(Instant)可以做到这一点。
static long hundredNanosUntil(Instant begin, Instant end) {
long secsDiff = Math.subtractExact(end.getEpochSecond(), begin.getEpochSecond());
long totalHundredNanos = Math.multiplyExact(secsDiff, 10_000_000);
return Math.addExact(totalHundredNanos, (end.getNano() - begin.getNano()) / 100);
}
static final Instant dotNetEpoch = ZonedDateTime.of(1, 1, 1, 0, 0, 0, 0,
ZoneOffset.UTC).toInstant();
static long toDotNetDateTimeTicks(Instant i) {
return hundredNanosUntil(dotNetEpoch, i);
}发布于 2018-12-20 02:57:03
记住1Tick等于100 ns,并在这里使用Eugene Beresovsky solution的符号是使用Duration类的另一个解决方案,以及从.Net ticks到Instant的转换。
static final Instant dotNetEpoch = ZonedDateTime.of(1, 1, 1, 0, 0, 0, 0,
ZoneOffset.UTC).toInstant();
// Converts Instant to .NET Tick
static long toDotNetDateTimeTicks(Instant i) {
Duration d =Duration.between(dotNetEpoch, i);
long secTix =Math.multiplyExact(d.getSeconds(), 10_000_000) ;
long nanoTix = d.getNano()/ 100 ;
long tix = Math.addExact(secTix,nanoTix);
return tix;
}
// Converts .NET Tick to Instant
static Instant toInstantFromDotNetDateTimeTicks(long dotNetTicks) {
long millis =Math.floorDiv(dotNetTicks,10000) ;
long restTicks = Math.floorMod(dotNetTicks,10000);
long restNanos =restTicks*100;
return dotNetEpoch.plusMillis(millis).plusNanos(restNanos);
}https://stackoverflow.com/questions/49020567
复制相似问题