Javascript 用javascript时间创建一个唯一的数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8012002/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create a unique number with javascript time
提问by Nick Petrie
I need to generate unique id numbers on the fly using javascript. In the past, I've done this by creating a number using time. The number would be made up of the four digit year, two digit month, two digit day, two digit hour, two digit minute, two digit second, and three digit millisecond. So it would look something like this: 20111104103912732 ... this would give enough certainty of a unique number for my purposes.
我需要使用 javascript 动态生成唯一的 ID 号。过去,我通过使用时间创建一个数字来做到这一点。该数字将由四位数的年份、两位数的月份、两位数的日、两位数的小时、两位数的分钟、两位数的秒和三位位数的毫秒组成。所以它看起来像这样: 20111104103912732 ...这将为我的目的提供足够的唯一数字的确定性。
It's been a while since I've done this and I don't have the code anymore. Anyone have the code to do this, or have a better suggestion for generating a unique ID?
我已经有一段时间没有这样做了,我不再有代码了。任何人都有执行此操作的代码,或者对生成唯一 ID 有更好的建议?
采纳答案by Marc B
If you just want a unique-ish number, then
如果你只想要一个独特的数字,那么
var timestamp = new Date().getUTCMilliseconds();
would get you a simple number. But if you need the readable version, you're in for a bit of processing:
会给你一个简单的数字。但是,如果您需要可读版本,则需要进行一些处理:
var now = new Date();
timestamp = now.getFullYear().toString(); // 2011
timestamp += (now.getMonth < 9 ? '0' : '') + now.getMonth().toString(); // JS months are 0-based, so +1 and pad with 0's
timestamp += ((now.getDate < 10) ? '0' : '') + now.getDate().toString(); // pad with a 0
... etc... with .getHours(), getMinutes(), getSeconds(), getMilliseconds()
回答by 3lRicko
A better approach would be:
更好的方法是:
new Date().valueOf();
instead of
代替
new Date().getUTCMilliseconds();
valueOf()is "most likely" a unique number. http://www.w3schools.com/jsref/jsref_valueof_date.asp.
valueOf()是“最有可能”的唯一数字。 http://www.w3schools.com/jsref/jsref_valueof_date.asp。
回答by Marcelo Lazaroni
The shortest way to create a number that you can be pretty sure will be unique among as many separate instances as you can think of is
创建一个您可以确定的数字的最短方法在您能想到的尽可能多的单独实例中是唯一的
Date.now() + Math.random()
If there is a 1 millisecond difference in function call, it is 100% guaranteed to generate a different number. For function calls within the same millisecond you should only start to be worried if you are creating more than a few million numbers within this same millisecond, which is not very probable.
如果函数调用有 1 毫秒的差异,则100% 保证生成不同的数字。对于同一毫秒内的函数调用,如果您在同一毫秒内创建超过几百万个数字,您应该开始担心,这不太可能。
For more on the probability of getting a repeated number within the same millisecond see https://stackoverflow.com/a/28220928/4617597
有关在同一毫秒内获得重复数字的概率的更多信息,请参阅https://stackoverflow.com/a/28220928/4617597
回答by August Lilleaas
This can be achieved simply with the following code:
这可以通过以下代码简单地实现:
var date = new Date();
var components = [
date.getYear(),
date.getMonth(),
date.getDate(),
date.getHours(),
date.getMinutes(),
date.getSeconds(),
date.getMilliseconds()
];
var id = components.join("");
回答by frumbert
Here's what I do when I want something smaller than a bunch of numbers - change base.
当我想要比一堆数字更小的东西时,这就是我所做的 - 改变基数。
var uid = (new Date().getTime()).toString(36)
回答by Steven Vachon
This performs faster than creating a Date
instance, uses less code and will alwaysproduce a unique number (locally):
这比创建一个Date
实例执行得更快,使用更少的代码并且总是会产生一个唯一的数字(本地):
function uniqueNumber() {
var date = Date.now();
// If created at same millisecond as previous
if (date <= uniqueNumber.previous) {
date = ++uniqueNumber.previous;
} else {
uniqueNumber.previous = date;
}
return date;
}
uniqueNumber.previous = 0;
jsfiddle: http://jsfiddle.net/j8aLocan/
jsfiddle:http: //jsfiddle.net/j8aLocan/
I've released this on Bower and npm: https://github.com/stevenvachon/unique-number
我已经在 Bower 和 npm 上发布了这个:https: //github.com/stevenvachon/unique-number
You could also use something more elaborate such as cuid, puidor shortidto generate a non-number.
回答by BaleineBleue
I use
我用
Math.floor(new Date().valueOf() * Math.random())
So if by any chance the code is fired at the same time there is also a teeny chance that the random numbers will be the same.
因此,如果有任何机会同时触发代码,那么随机数相同的可能性很小。
回答by FacePalm
This should do :
这应该做:
var uniqueNumber = new Date().getTime(); // milliseconds since 1st Jan. 1970
回答by Raj Rj
if you want a unique number after few mili seconds then use Date.now()
, if you want to use it inside a for loop
then use Date.now() and Math.random()
together
如果你想在几毫秒后得到一个唯一的数字然后使用Date.now()
,如果你想在 a 中使用它for loop
然后Date.now() and Math.random()
一起使用
unique number inside a for loop
for 循环中的唯一编号
function getUniqueID(){
for(var i = 0; i< 5; i++)
console.log(Date.now() + ( (Math.random()*100000).toFixed()))
}
getUniqueID()
output:: all numbers are unique
输出::所有数字都是唯一的
15598251485988384
155982514859810330
155982514859860737
155982514859882244
155982514859883316
15598251485988384
155982514859810330
155982514859860737
155982514859882244
155982514859883316
unique number without Math.random()
唯一编号没有 Math.random()
function getUniqueID(){
for(var i = 0; i< 5; i++)
console.log(Date.now())
}
getUniqueID()
output:: Numbers are repeated
输出::重复数字
1559825328327
1559825328327
1559825328327
1559825328328
1559825328328
1559825328327
1559825328327
1559825328327
1559825328328
1559825328328
回答by abarber
From investigating online I came up with the following object that creates a unique id per session:
通过在线调查,我想出了以下为每个会话创建唯一 ID 的对象:
window.mwUnique ={
prevTimeId : 0,
prevUniqueId : 0,
getUniqueID : function(){
try {
var d=new Date();
var newUniqueId = d.getTime();
if (newUniqueId == mwUnique.prevTimeId)
mwUnique.prevUniqueId = mwUnique.prevUniqueId + 1;
else {
mwUnique.prevTimeId = newUniqueId;
mwUnique.prevUniqueId = 0;
}
newUniqueId = newUniqueId + '' + mwUnique.prevUniqueId;
return newUniqueId;
}
catch(e) {
mwTool.logError('mwUnique.getUniqueID error:' + e.message + '.');
}
}
}
It maybe helpful to some people.
它可能对某些人有帮助。
Cheers
干杯
Andrew
安德鲁