javascript generate random number based on date

JavaScript: Generate Random Number Based on Date

Generating random numbers in JavaScript is a common task for many developers. One approach to generating a random number is to use the current date as a seed value.

Using Math.random() Method

The Math.random() method generates a random number between 0 and 1. We can use this method to generate a random number based on the current date by multiplying the output of Math.random() by the current date and then converting the result to an integer using the Math.floor() method.


let currentDate = new Date();
let randomNum = Math.floor(Math.random() * currentDate);
console.log(randomNum);

Using Date.now() Method

The Date.now() method returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. We can use this method to generate a random number based on the current date by taking the modulus of the output of Date.now() with a large number and then adding 1 to avoid getting a value of 0.


let randomNum = (Date.now() % 100000) + 1;
console.log(randomNum);

Both of these methods will generate a random number based on the current date. However, it's important to note that neither of these methods guarantee true randomness and should not be used for security purposes.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe