Java 获取随机数生成器种子的当前日期时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3535574/
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
Getting Current Date Time for a Random Number Generator's Seed
提问by bobber205
Preferably as a long.
最好是长的。
All the example I can find are getting the date/time as a string and not any scalar value. :)
我能找到的所有示例都是将日期/时间作为字符串而不是任何标量值。:)
采纳答案by Greg Hewgill
If you reallywant the current time as a long, try System.currentTimeMillis()
. Alternatively, you can use new Date().getTime()
.
如果您真的希望当前时间很长,请尝试System.currentTimeMillis()
. 或者,您可以使用new Date().getTime()
.
However, using the current time as a random number generator seed is a very poor choice (at least, if you are using the random numbers for anything important, such as cryptography). You may wish to consider using a random source such as /dev/urandom
(if available on your platform).
但是,使用当前时间作为随机数生成器种子是一个非常糟糕的选择(至少,如果您将随机数用于任何重要的事情,例如密码学)。您可能希望考虑使用随机源,例如/dev/urandom
(如果在您的平台上可用)。
回答by Peter Tillemans
System.currentTimeMillis returns a long.
System.currentTimeMillis 返回一个 long。
http://download.oracle.com/javase/1.5.0/docs/api/java/lang/System.html#currentTimeMillis()
http://download.oracle.com/javase/1.5.0/docs/api/java/lang/System.html#currentTimeMillis()
there is also System.nanoTime().
还有 System.nanoTime()。
回答by sujeetgandhi
To generate a random number you can use this code:
要生成随机数,您可以使用以下代码:
var randomnumber=new Date().getUTCMilliseconds();
var rand = Math.floor((Math.random() * randomnumber) + 1);
document.write(rand);