1

I need to convert an Instant into .Net's DateTime.Ticks, i.e. a long that represents the number of one-hundred nanoseconds since 0:00:00 UTC on January 1, 0001.

Unfortunately, there is no such thing as a ChronoUnit.HUNDRED_NANOS, so it seems one has to roll ones own code.

2 Answers 2

2

Having in mind that 1 tick equals 100 ns and using the notation of Eugene Beresovsky solution here is another solution using the Duration class, together with a conversion from .Net ticks to 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); } 
Sign up to request clarification or add additional context in comments.

2 Comments

thanks. but what is plusMillis and plusNanos? can you please explain them.
1

The function toDotNetDateTimeTicks(Instant) below does the trick.

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); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.