Search code examples
javac#timedatetime-conversionjava.time.instant

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


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

Reference: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-dtyp/cca27429-5689-4a16-b2b4-9325d93e4ba2

The FILETIME structure is a 64-bit value that represents the number of 100-nanosecond intervals that have elapsed since January 1, 1601, Coordinated Universal Time (UTC). typedef struct _FILETIME { DWORD dwLowDateTime; DWORD dwHighDateTime; } FILETIME, *PFILETIME, *LPFILETIME; dwLowDateTime: A 32-bit unsigned integer that contains the low-order bits of the file time. dwHighDateTime: A 32-bit unsigned integer that contains the high-order bits of the file time.

For example, here is the long 130280867040000000

So the the high and low computed with

int high = (int)(fullval >> 32);
int low = (int)fullval;

so high = 30333378 and low = 552794112

How do I compute these to a Java 8 Instant?


Solution

  • 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.