Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract timestamp from UUID v1 (TimeUUID) using javascript?

I use Cassandra DB and Helenus module for nodejs to operate with this. I have some rows which contains TimeUUID columns. How to get timestamp from TimeUUID in javascript?

like image 213
Vadim Avatar asked Jul 10 '13 12:07

Vadim


People also ask

Can I get timestamp from UUID?

You can use the unixTimestampOf or dateOf functions in CQL3, or you can do it yourself, the hard way: The time is encoded into the top 64 bits of the UUID, but it's interleaved with some other pieces, so it's not super straight forward to extract a time.

Can you get date from UUID?

In order to get a meaningful date from a UUID, you'll need to do two things: convert from 100ns to 1ms precision (divide by 10000) and rebase from 1582-10-15 to 1970-01-01, which you can do by adding a constant value.

What is Timeuuid?

TIMEUUID is a universal unique identifier variant that includes time information.


2 Answers

Use uuid-time module.

I asked maintainers of uuid module here https://github.com/kelektiv/node-uuid/issues/297 and they pointed me to the uuid-time module https://www.npmjs.com/package/uuid-time

like image 109
Aalex Gabi Avatar answered Sep 28 '22 18:09

Aalex Gabi


this lib ( UUID_to_Date ) is very simple and fast!! only used native String function. maybe this Javascript API can help you to convert the UUID to date format, Javascript is simple language and this simple code can help to writing API for every language.

this API convert UUID v1 to sec from 1970-01-01



all of you need:

    get_time_int = function (uuid_str) {
        var uuid_arr = uuid_str.split( '-' ),
            time_str = [
                uuid_arr[ 2 ].substring( 1 ),
                uuid_arr[ 1 ],
                uuid_arr[ 0 ]
            ].join( '' );
        return parseInt( time_str, 16 );
    };

    get_date_obj = function (uuid_str) {
        var int_time = this.get_time_int( uuid_str ) - 122192928000000000,
            int_millisec = Math.floor( int_time / 10000 );
        return new Date( int_millisec );
    };


Example:

    var date_obj = get_date_obj(  '8bf1aeb8-6b5b-11e4-95c0-001dba68c1f2' );
    date_obj.toLocaleString( );// '11/13/2014, 9:06:06 PM'
like image 26
Sam Avatar answered Sep 28 '22 16:09

Sam