'Get the UNIX timestamp from UUID version 1

In our Java application we are trying to get the UNIX time from the UUID version 1. But it's not giving the correct date time values.

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();

Can someone please help?



Solution 1:[1]

If you using datastax driver, it's:

UUIDs.unixTimestamp(uuid)

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

Solution 2:[2]

In my case, the following code worked.

    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

Solution 3:[3]

How to extract time from UUIDs using UuidUtil from uuid-creator:

Instant instant = UuidUtil.getInstant(uuid);

long secs = instant.getEpochSecond(); // seconds since 1970-01-01
long msecs = instant.toEpochMilli(); // millis since 1970-01-01

Solution 4:[4]

In MySQL:

SET 
  @t0:=SYSDATE(6)
, @u0:=UUID()
, @t1:=SYSDATE(6)
; SELECT 
  @u0 AS _u0
, @u1:=CONCAT(SUBSTR(@u0,16,3),SUBSTR(@u0,10,4),SUBSTR(@u0,1,8)) AS _u1
, @t0 AS _t0
, FROM_UNIXTIME(CONV(@u1,16,10)/1e7-12219292800) AS _tu
, @t1 AS _t1 \G

Query OK, 0 rows affected (0.00 sec)

*************************** 1. row ***************************
_u0: 060e0537-ce21-11ec-9807-525400432b3b
_u1: 1ecce21060e0537
_t0: 2022-05-07 18:16:17.246698
_tu: 2022-05-07 18:16:17.246750
_t1: 2022-05-07 18:16:17.246755
1 row in set (0.00 sec)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user3324777
Solution 2 Md Manawyal Haque
Solution 3
Solution 4 druud62