Generate random date with JavaScript
Question:
How to generate random date with JavaScript? Answer:
function getRandomDate() {
const maxDate = Date.now();
const timestamp = Math.floor(Math.random() * maxDate);
return new Date(timestamp);
}
console.log(getRandomDate());
Description:
To generate a random date you can use the Math.random
function and the fact that a Date
can be created from a timestamp that is an integer number of milliseconds elapsed since January 1, 1970 00:00:00 UTC
You need to set a max value, for example, the actual date's timestamp, and use it to generate a new, random number. With this new timestamp value, you can create a new Date object using it as a constructor parameter.
Note: This solution generates random dates only from the date January 1, 1970.
Reference:
Math.random reference
Share "How to generate random date with JavaScript?"
Related snippets:
Tags:
date, random, generate, javascript Technical term:
Generate random date with JavaScript