Skip to main content

How to convert Cassandra Timestamp UUID to Date in Java

Using Cassandra with Java is an awesome experience. Write queries are super fast and clustering support is easy to setup and its really impressive how salable Cassandra's architecture is.

Yesterday I got into an issue of fetching timeuuid from a table called logs_all. Below is the table definition if you are interested

CREATE TABLE logs_all (
    msisdn bigint,
    transaction_id text,
    timestamp timeuuid,
    action text,
    event text,
    PRIMARY KEY ((msisdn, transaction_id), timestamp)
)

I needed to convert timeuuid to java date time and apparently java driver doesn't provide a
row.getDate() method. So I used the following code.

           UUID timestamp = row.getUUID("timestamp");
            Long longTimstamp =  UUIDs.unixTimestamp(timestamp);
            java.util.Date time=new java.util.Date((long)longTimstamp);

Full Code below:

String cassandraQuery = "Select * from logs_all;";
ResultSet results = null;
        try {
            results = CassandraClient.getInstance().execute(cassandraQuery);
        } catch (PropertyNotFoundException ex) {
            log.error(ex.getMessage());
        } catch (Exception ex) {
            log.error(ex.getMessage());
        }
        if (results == null) {
            log.info("No results found... exiting");
            CassandraClient.getInstance().getSession().close();
            return;
        }
        Iterator iter = results.iterator();
        while (iter.hasNext()) {
            Row row = iter.next();
            UUID timestamp = row.getUUID("timestamp");
            Long longTimstamp =  UUIDs.unixTimestamp(timestamp);
            java.util.Date time=new java.util.Date((long)longTimstamp);
}

Comments