Skip to content

UUIDUtil.extractTimestamp() is broken for versions 1 and 6 #105

Closed
@gabrielbalan

Description

@gabrielbalan

UUIDUtil.extractTimestamp() returns bad result for Generators.timeBasedGenerator() and Generators.timeBasedReorderedGenerator() in version 5.0.0.

The javadoc says

@return timestamp in milliseconds (since Epoch), or 0 if type does not support timestamps

Which makes me think I should be able to compare the milliseconds returned by UUIDUtil.extractTimestamp() against System.currentTimeMillis().

Here's the reproducer:

    @Test
    public void testExtractTimestampFromTimeBasedUUID() {
        testExtractTimestamp(Generators.timeBasedGenerator());
    }
    @Test
    public void testExtractTimestampFromTimeBasedReorderedUUID() {
        testExtractTimestamp(Generators.timeBasedReorderedGenerator());
    }
    @Test
    public void testExtractTimestampFromTimeBasedEpochdUUID() {
        testExtractTimestamp(Generators.timeBasedEpochGenerator());
    }

    public void testExtractTimestamp( NoArgGenerator generator){

        long before = System.currentTimeMillis();
        UUID timeBasedUUID =  generator.generate();
        long after = System.currentTimeMillis();

        long extracted = UUIDUtil.extractTimestamp(timeBasedUUID);
        if(extracted < before || extracted > after)
        {
            System.err.println("System.currentTimeMillis() before generate UUID: " + before);
            System.err.println("System.currentTimeMillis() after generate UUID:  " + after);
            System.err.println("UIDUtil.extractTimestamp from generated UUID:    " + extracted);
        }
        Assert.assertTrue(extracted>=before);
        Assert.assertTrue(extracted<=after);
    }

And here is the output:

System.currentTimeMillis() before generate UUID:  1715956528376
System.currentTimeMillis() after generate UUID:   1715956528376
UIDUtil.extractTimestamp from generated UUID:    139352493283760061

System.currentTimeMillis() before generate UUID:  1715956528397
System.currentTimeMillis() after generate UUID:   1715956528397
UIDUtil.extractTimestamp from generated UUID:    139352493283970062

I believe that UUIDUtil.extractTimestamp() returns

  • milliseconds since midnight, January 1, 1970 UTC (unix epoch) for timeBasedEpochGenerator;
  • hundreds of nanoseconds since since 00:00:00.00,15 October 1582 (the date of Gregorian reform to the Christian calendar) for timeBasedGenerator and timeBasedReorderedGenerator.

Therefore the fix for the two affected formats should be to divide by 10'000 and subtract the time-distance (in ms) between the gregorian epoch and the unix epoch.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions