8

在我们的 Java 应用程序中,我们试图从 UUID版本 1中获取 UNIX 时间。但它没有给出正确的日期时间值。

long time = uuid.timestamp();
time = time / 10000L;   // Dividing by 10^4 as it's in 100 nanoseconds precision 
Calendar c = Calendar.getInstance();
c.setTimeInMillis(time);
c.getTime();

有人可以帮忙吗?

4

4 回答 4

16

从文档中timestamp()

生成的时间戳从 UTC 1582 年 10 月 15 日午夜开始以 100 纳秒为单位进行测量。

所以你需要抵消它。例如:

Calendar uuidEpoch = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
uuidEpoch.clear();
uuidEpoch.set(1582, 9, 15, 0, 0, 0); // 9 = October
long epochMillis = uuidEpoch.getTime().getTime();

long time = (uuid.timestamp() / 10000L) + epochMillis;
// Rest of code as before
于 2012-10-25T14:27:02.830 回答
6

如果您使用 datastax 驱动程序,它是:

UUIDs.unixTimestamp(uuid)

http://www.datastax.com/drivers/java/2.0/com/datastax/driver/core/utils/UUIDs.html#unixTimestamp(java.util.UUID)

于 2014-05-27T18:56:07.993 回答
0

就我而言,以下代码有效。

    final long NUM_100NS_INTERVALS_SINCE_UUID_EPOCH = 0x01b21dd213814000L;
    UUID uuid = UUID.fromString("6470d760-d93d-11e9-8b32-858313a776ba");
    long  time = (uuid.timestamp() - NUM_100NS_INTERVALS_SINCE_UUID_EPOCH) / 10000;
    // Rest of code as before
于 2019-09-17T11:36:05.493 回答
0

如何使用uuid-creatorUuidUtil从UUID 中提取时间:

Instant instant = UuidUtil.getInstant(uuid);

long secs = instant.getEpochSecond(); // seconds since 1970-01-01
long msecs = instant.toEpochMilli(); // millis since 1970-01-01
于 2019-09-23T05:30:52.000 回答