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

邮差的信 提交于 2020-02-20 08:28:21

问题


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?


回答1:


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'



回答2:


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.

If n is the integer representation of the TimeUUID then you can extract the UNIX epoch like this:

n = (value >> 64)
t = 0
t |= (n & 0x0000000000000fff) << 48
t |= (n & 0x00000000ffff0000) << 16
t |= (n & 0xffffffff00000000) >> 32
t -= 122192928000000000
seconds = t/10_000_000
microseconds = (t - seconds * 10_000_000)/10.0

this code is from my Ruby CQL3 driver, cql-rb, and can be found in full here: https://github.com/iconara/cql-rb/blob/master/lib/cql/time_uuid.rb

I used this resource: http://www.famkruithof.net/guid-uuid-timebased.html, and the RFC to implement that code.




回答3:


node-uuid module for nodejs contains method for convert uuid v1 to timestamp

Commit with function for extract msecs from uuid v1




回答4:


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



来源:https://stackoverflow.com/questions/17571100/how-to-extract-timestamp-from-uuid-v1-timeuuid-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!