When using Math.random()
in JavaScript we create a random number between 0 and less than 1. What if we want to create a random number that is greater than 1, how do we go about that?
In this blog post, we will create a random number leveraging the Date constructor along with Math.random()
.
const createNewRandomNumber = new Date(
new Date().valueOf() - Math.random() * 1e12
)
.valueOf();
console.log(createNewRandomNumber); //792477825949
In the above code snippet, we leverage the Date constructor using new Date()
and within it we get the current date and time as milliseconds new Date().valueOf()
since Epoch (i.e. January 1, 1970). We then utilize Math.random()
and multiply it by 1e12
in order to generate a random number in milliseconds, which can go up to a trillion and then subtract the results of the multiplication from the current date time that we created using new Date().valueOf()
. The result is then outputted in a Date object and then outputted in numeric format valueOf()
.