Skip to content

Instantly share code, notes, and snippets.

@hshimo
Last active December 27, 2015 12:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hshimo/7329528 to your computer and use it in GitHub Desktop.
Save hshimo/7329528 to your computer and use it in GitHub Desktop.
get time from uuid.v1 string
/**
* extract time from uuid.v1 string
*
* originally from
* node-uuid/uuid.js at master · krassif/node-uuid
* https://github.com/krassif/node-uuid/blob/master/uuid.js
*
* @param buf buffer
* @param offset offset
* @returns {number} msec
*/
// extracts time (msecs) from v1 type uuid
function v1time(buf, offset) {
var msec = 0, nsec = 0;
var i = buf && offset || 0;
var b = buf||[];
// inspect version at offset 6
if ((b[i+6]&0x10)!=0x10) {
throw new Error("uuid version 1 expected"); }
// 'time_low'
var tl = 0;
tl |= ( b[i++] & 0xff ) << 24;
tl |= ( b[i++] & 0xff ) << 16;
tl |= ( b[i++] & 0xff ) << 8;
tl |= b[i++] & 0xff ;
// `time_mid`
var tmh = 0;
tmh |= ( b[i++] & 0xff ) << 8;
tmh |= b[i++] & 0xff;
// `time_high_minus_version`
tmh |= ( b[i++] & 0xf ) << 24;
tmh |= ( b[i++] & 0xff ) << 16;
// account for the sign bit
msec = 1.0 * ( ( tl >>> 1 ) * 2 + ( ( tl & 0x7fffffff ) % 2 ) ) / 10000.0;
msec += 1.0 * ( ( tmh >>> 1 ) * 2 + ( ( tmh & 0x7fffffff ) % 2 ) ) * 0x100000000 / 10000.0;
// Per 4.1.4 - Convert from Gregorian epoch to unix epoch
msec -= 12219292800000;
// getting the nsec. they are not needed now though
// nsec = ( tl & 0xfffffff ) % 10000;
return msec;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment