DataStax Help Center

Converting TimeUUID Strings to Dates

TimeUUID is one of the datatypes supported by Cassandra. The Cassandra JDBC driver will return a hexadecimal representation of the UUID rather than a human-readable date.  You can use the java.util.UUID and java.util.Date classes to convert from a TimeUUID string to a Date. The UUID.timestamp() returns a long containing the timestamp value associated with this UUID. The resulting timestamp is measured in 100-nanosecond units since midnight, October 15, 1582 UTC. Notice that this is a different epoch and resolution than the long expected by Date's constructor, which is the number of milliseconds since January 1, 1970, 00:00:00 GMT. Therefore, the conversion requires some math. Here is some example code to convert from a string representing a TimeUUID string to a java.util.Date object:

import java.util.Date;
import java.util.UUID;

public class UUIDToDate {
  // This method comes from Hector's TimeUUIDUtils class:
  // https://github.com/rantav/hector/blob/master/core/src/main/java/me/prettyprint/cassandra/utils/TimeUUIDUtils.java
  static final long NUM_100NS_INTERVALS_SINCE_UUID_EPOCH = 0x01b21dd213814000L;
  public static long getTimeFromUUID(UUID uuid) {
    return (uuid.timestamp() - NUM_100NS_INTERVALS_SINCE_UUID_EPOCH) / 10000;
  }

  public static void main(String[] args) {
    String uuidString = "28442f00-2e98-11e2-0000-89a3a6fab5ef";
    UUID uuid = UUID.fromString(uuidString);
    long time = getTimeFromUUID(uuid);
    Date date = new Date(time);
    System.out.println(date);
  }
}
Was this article helpful?
1 out of 1 found this helpful
Have more questions? Submit a request

Comments

Powered by Zendesk