开发者

Create a UUID from Timestamp (as number)

开发者 https://www.devze.com 2023-03-14 14:51 出处:网络
How can I create a开发者_StackOverflow UUID from the Timestamp number using Javascript? Is there any existente API?According to the Wikipedia page, a UUID is a 128-bit number. Javascript numbers are

How can I create a开发者_StackOverflow UUID from the Timestamp number using Javascript?

Is there any existente API?


According to the Wikipedia page, a UUID is a 128-bit number. Javascript numbers are 64-bit floating point numbers (according to this SO answer), so I assume that you already have your UUID number in the form of a string.

Quoting Wikipedia: "a UUID consists of 32 hexadecimal digits, displayed in 5 groups separated by hyphens, in the form 8-4-4-4-12 for a total of 36 characters (32 digits and 4 hyphens)." Javascript Number's toString method can be given a base (hexadecimal is base 16) but of course we can't use Numbers here.

So, you'll need some sort of code that can first handle 128-bit numbers and then convert them to hexadecimal. There are various BigDecimal and BigNumber Javascript libraries knocking about. Just find one that you like, perhaps using a SO question as a guide. Having done that you'll have a string like so:

var hexNum = "550e8400e29b41d4a716446655440000";

Then you simple combine the different substrings with - separators and you have your UUID string:

var UUID = hexNum.substr(0, 8) + '-' +  hexNum.substr(8, 4) + '-' + 
  hexNum.substr(12, 4) + '-' + hexNum.substr(16, 4) + '-' + hexNum.substr(20)

Update: In the process of writing my response the original question was updated to ask how you'd create a UUID from a 'Timestamp number'. I'm not sure what that'd be, perhaps a Unix timestamp, for instance the result of Date.now(). Since UUIDs are supposed to be (practically) unique and a millisecond time is hardly unique, I'd imagine you'd want to introduce some further element of uniqueness into the number before creating the number. Even if you didn't, you'd still need to convert 64-bit Number to a 128-bit number, again using some sort of BigDecimal or BigNumber library.

0

精彩评论

暂无评论...
验证码 换一张
取 消