从时间戳创建 UUID(作为数字)
如何使用 Javascript 从时间戳数字创建 UUID?
有没有现成的API?
How can I create a UUID from the Timestamp number using Javascript?
Is there any existente API?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据 维基百科页面,UUID 是一个 128 位数字。 JavaScript 数字是 64 位浮点数 (根据这个SO答案),所以我假设你已经有了字符串形式的UUID号。
引用维基百科:“UUID 由 32 个十六进制数字组成,以连字符分隔的 5 组显示,形式为 8-4-4-4-12,总共 36 个字符(32 个数字和 4 个连字符)。” Javascript
Number
的toString
方法可以被赋予一个基数(十六进制是基数 16),但是我们当然不能在这里使用Number
。因此,您需要某种代码来首先处理 128 位数字,然后将它们转换为十六进制。有各种 BigDecimal 和 BigNumber Javascript 库。只需找到一个您喜欢的问题,也许可以使用一个SO问题作为指导。完成后,您将得到一个如下所示的字符串:
然后您只需将不同的子字符串与
-
分隔符组合起来,就得到了您的 UUID 字符串:更新: 在编写过程中我的回答是,原始问题已更新为询问如何从“时间戳数字”创建 UUID。我不确定那是什么,也许是 Unix 时间戳,例如
Date.now()
的结果。由于 UUID 应该(实际上)是唯一的,并且毫秒时间几乎不是唯一的,因此我想您希望在创建数字之前在数字中引入一些进一步的唯一性元素。即使不这样做,您仍然需要将 64 位Number
转换为 128 位数字,再次使用某种 BigDecimal 或 BigNumber 库。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
'stoString
method can be given a base (hexadecimal is base 16) but of course we can't useNumber
s 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:
Then you simple combine the different substrings with
-
separators and you have your UUID string: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-bitNumber
to a 128-bit number, again using some sort of BigDecimal or BigNumber library.