How do you represent MS-DTYP `DATETIME` in Java 8 Instant?

前端 未结 2 1348
面向向阳花
面向向阳花 2021-01-22 11:19

In the Microsoft Spec, DATETIME is represented as 2 32-bit integers: low and high

Reference: https://docs.microsoft.com/en-us/open

2条回答
  •  北海茫月
    2021-01-22 12:18

    For converting with 1 second precision your own answer is just fine. In case you also need to convert the fraction of second, here’s one way to do that.

        Instant msFiletimeEpoch = Instant.parse("1601-01-01T00:00:00Z");
        // a tick is 100 nanoseconds
        int nanosPerTick = 100;
        long ticksPerSecond = TimeUnit.SECONDS.toNanos(1) / nanosPerTick;
    
        long fullval = 130_280_867_040_000_000L;
    
        long seconds = fullval / ticksPerSecond;
        long nanos = fullval % ticksPerSecond * nanosPerTick;
    
        Instant answer = msFiletimeEpoch.plusSeconds(seconds).plusNanos(nanos);
    
        System.out.println(answer);
    

    Output is:

    2013-11-05T00:58:24Z

    Let’s try to put 1 more tick on your oroginal value; it should add 100 nanoseconds.

        long fullval = 130_280_867_040_000_001L;
    

    2013-11-05T00:58:24.000000100Z

    So so it does.

    Caveat for very far future dates: According to your quote the Microsoft integers are both unsigned. A Java long is signed. So some time in year 30828 we will start getting results that are very wrong. Just in case we ought to throw an exception if the long value is negative.

提交回复
热议问题