Generate random date in a range with JavaScript
Question:
How to generate random date in a range with JavaScript? Answer:
function getRandomDate(startDate, endDate) {
const minValue = startDate.getTime();
const maxValue = endDate.getTime();
const timestamp = Math.floor(Math.random() * (maxValue - minValue + 1) + minValue);
return new Date(timestamp);
}
console.log(getRandomDate(new Date(2020,0,1), new Date(2029,11,31))); // Thu Jun 17 2027 23:13:22 GMT+0200
Description:
Generating a date in a range can be simplified to generating a number in a range as a Date
can be created from a timestamp value. So you can easily write a function that accepts a start date and an end date. Convert them to a timestamp and use these values with Math.random
to generate a number in that range. With this new number, you can easily create a new Date object using it as a constructor parameter.
Reference:
Math.random reference
Share "How to generate random date in a range with JavaScript?"
Related snippets:
Tags:
date, random, range, interval, generate, javascript Technical term:
Generate random date in a range with JavaScript