8

Preferably as a long.

All the example I can find are getting the date/time as a string and not any scalar value. :)

stacker
  • 68,052
  • 28
  • 140
  • 210
bobber205
  • 12,948
  • 27
  • 74
  • 100

3 Answers3

17

If you really want the current time as a long, try System.currentTimeMillis(). Alternatively, you can use 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).

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
  • 14
    Note also that the standard Java random number generator, java.util.Random, by default initializes to System.currentTimeMillis(), so if that's the generator you're using, no need to do that explicitly. – William Pietri Aug 20 '10 at 23:50
  • 1
    Security is most definitely NOT important. It's justing ordering of some questions, which up until this point had be done by some constants. :P – bobber205 Aug 20 '10 at 23:50
  • 4
    Java has java.security.SecureRandom, so there is no need to use /dev/urandom directly. http://download.oracle.com/javase/6/docs/api/java/security/SecureRandom.html – starblue Aug 21 '10 at 07:53
  • @WilliamPietri is it [documented](http://docs.oracle.com/javase/7/docs/api/java/util/Random.html), or internals? – Ciro Santilli OurBigBook.com Feb 11 '15 at 15:22
1

System.currentTimeMillis returns a long.

http://download.oracle.com/javase/1.5.0/docs/api/java/lang/System.html#currentTimeMillis()

there is also System.nanoTime().

Peter Tillemans
  • 34,983
  • 11
  • 83
  • 114
0

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);
ᗩИᎠЯƎᗩ
  • 2,122
  • 5
  • 29
  • 41