我如何从UUID类型1获取日期/时间

时间:2018-06-30 17:42:49

标签: java timeuuid

我已包含以下UUID库     编译组:“ com.fasterxml.uuid”,名称:“ java-uuid-generator”,版本:“ 3.1.5”  在我的构建中。

我有一些这样的代码

        NoArgGenerator timeBasedGenerator = Generators.timeBasedGenerator()
        UUID tuid = timeBasedGenerator.generate()
        Timestamp timestamp = new Timestamp ((tuid.timestamp()/1000) as Long)
        Date dateTime = new Date (timestamp.getTime())

但是,当它迭代并查看日期时,它与应有的样子完全不同,例如,我得到“ uid fef57eca-7c8b-11e8-bedd-992c2ac3197a是Sun Feb 06 07:55:54 GMT 6327”,而今天是30 / 06/2018

有人知道如何使用fasterxml.uuid库从基于时间的UUID正确提取实际日期和时间吗?

但被困

ps试试了

        UUID tuid = timeBasedGenerator.generate()
        Long t = tuid.timestamp()
        Timestamp timestamp = new Timestamp (t)
        Date dateTime = new Date (timestamp.getTime())

给出了一个uid ff79d7d9-7cb5-11e8-976c-6ba57a5e9636和日期,Thu Aug 14 11:11:40 BST 4359073

3 个答案:

答案 0 :(得分:2)

要获得完整的 100ns 精度作为 java.util.Instant,您可以执行以下操作:

private static final long NUM_HUNDRED_NANOS_IN_A_SECOND = 10_000_000L;

private static final long NUM_HUNDRED_NANOS_FROM_UUID_EPOCH_TO_UNIX_EPOCH = 122_192_928_000_000_000L;


/**
 * Extracts the Instant (with the maximum available 100ns precision) from the given time-based (version 1) UUID.
 *
 * @return the {@link Instant} extracted from the given time-based UUID
 * @throws UnsupportedOperationException If this UUID is not a version 1 UUID
 */
public static Instant getInstantFromUUID(final UUID uuid) {
    final long hundredNanosSinceUnixEpoch = uuid.timestamp() - NUM_HUNDRED_NANOS_FROM_UUID_EPOCH_TO_UNIX_EPOCH;
    final long secondsSinceUnixEpoch = hundredNanosSinceUnixEpoch / NUM_HUNDRED_NANOS_IN_A_SECOND;
    final long nanoAdjustment = ((hundredNanosSinceUnixEpoch % NUM_HUNDRED_NANOS_IN_A_SECOND) * 100);
    return Instant.ofEpochSecond(secondsSinceUnixEpoch, nanoAdjustment);
}

答案 1 :(得分:1)

我在网上做了更多搜索。

我构建了以下“简单实用程序”类,可以根据需要进行扩展:

import com.fasterxml.uuid.Generators
import com.fasterxml.uuid.NoArgGenerator

class UuidUtil {

    static final NoArgGenerator timeBasedGenerator = Generators.timeBasedGenerator()


    /**
     * From UUID javadocs the resulting timestamp is measured in 100-nanosecond units since midnight, October 15, 1582 UTC
     * timestamp() from UUID is measured in 100-nanosecond units since midnight, October 15, 1582 UTC
     *
     * The Java timestamp in milliseconds since 1970-01-01 as baseline
     *
     * @return
     */
    static long getStartOfUuidRelativeToUnixEpochInMilliseconds () {
        Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT-0"))
        c.set(Calendar.YEAR, 1582)
        c.set(Calendar.MONTH, Calendar.OCTOBER)
        c.set(Calendar.DAY_OF_MONTH, 15)
        c.set(Calendar.HOUR_OF_DAY, 0)
        c.set(Calendar.MINUTE, 0)
        c.set(Calendar.SECOND, 0)
        c.set(Calendar.MILLISECOND, 0)

        return c.getTimeInMillis()
    }

    //https://www.wolframalpha.com/input/?i=convert+1582-10-15+UTC+to+unix+time
    final static long START_OF_UUID_RELATIVE_TO_UNIX_EPOCH_SECONDS = -12219292800L
    final static long START_OF_UUID_RELATIVE_TO_UNIX_EPOCH_MILLIS = -12219292800L * 1000L

    /**
     * timestamp() from UUID is measured in 100-nanosecond units since midnight, October 15, 1582 UTC,
     * so we must convert for 100ns units to millisecond procession
     * @param tuid
     * @return
     */
    static long getMillisecondsFromUuid (UUID tuid) {

        assert tuid.version() == 1      //ensure its a time based UUID

        // timestamp returns in 10^-7 (100 nano second chunks), 
        // java Date constructor  assumes 10^-3 (millisecond precision)
        // so we have to divide by 10^4 (10,000) to get millisecond precision  
        long milliseconds_since_UUID_baseline = tuid.timestamp() /10000L

    }

    static getDateFromUuid (UUID tuid) {
        // Allocates a Date object and initializes it to represent the specified number of milliseconds since the 
        // standard java (unix) base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT
        // have to add relative offset from UUID start date of unix epoch to get start date in unix time milliseconds 
        new Date (getMillisecondsFromUuid (tuid) + START_OF_UUID_RELATIVE_TO_UNIX_EPOCH_MILLIS )
    }

    static UUID getTimeBasedUuid () {
        UUID tuid = timeBasedGenerator.generate()
    }

}

我添加了解释性注释,以便您可以按照将UUID timestamp()方法处理为可用于常规Java日期和时间处理的格式的方式进行操作。

为什么Java UUID类无法提供可能期望使基于时间的UUID与基于常规unix纪元的常规java日期/时间格式互操作的方法,对我来说还是个谜。

我使用上述静态方法运行了一些测试脚本:

println "get start of epoch in milliseconds " + UuidUtil.getStartOfUuidRelativeToUnixEpochInMilliseconds()
assert UuidUtil.START_OF_UUID_RELATIVE_TO_UNIX_EPOCH_MILLIS == UuidUtil.startOfUuidRelativeToUnixEpochInMilliseconds

UUID tuid = UuidUtil.timeBasedUuid

println "uid : $tuid"

Date date = UuidUtil.getDateFromUuid(tuid)
println "extracted date from uid is " + UuidUtil.getDateFromUuid(tuid)

得到了

get start of epoch in milliseconds -12219292800000
uid : 43acb588-7d39-11e8-b37b-59f77bf2d333
extracted date from uid is Sun Jul 01 15:15:53 BST 2018

在运行脚本的时间看来正确。

答案 2 :(得分:0)

库'uuid-creator'具有一个实用程序类,该类有助于提取UUID部分,例如时间和节点ID。参见此示例:

long milliseconds = UuidUtil.extractUnixMilliseconds(uuid);

项目: https://github.com/f4b6a3/uuid-creator