In this article, we will how to generate a random date between two dates in JavaScript.

First, we should define the start and end date between which we want to generate a random date. We can do this in JavaScript easily by using the Date object.

In the following example, we have defined the start and date using the Date object

const startDate = new Date('2022-01-01');
const endDate = new Date('2022-12-31');

Now, we have to calculate the time difference between these time and convert this into milliseconds such that we can generate a random number within that range.

const timeDiff = endDate.getTime() - startDate.getTime();

By using the Math.random() method we can generate a random number between 0 and 1, and then multiply it by the time difference. This will give us a random number within the time difference.

const randomTime = Math.random() * timeDiff;

Now, by using a new Date Object we can add this random time to the start date.

const randomDate = new Date(startDate.getTime() + randomTime);

As a final step, we have to format the randomly generated date. The random which was generated above will be in the following format.

Mon Mar 28 2022 18:30:00 GMT-0700 (Pacific Daylight Time)

Based on the use case or requirement we can format the date. There are several in-build methods in the Date object to format the date. In the below example we use the “toISOString()” to the date in the format i.e. “YYYY-MM-DDTHH:mm:ss.sssZ“.

const formattedDate = randomDate.toISOString().slice(0, 10);

The slice method in the above example extracts the first 10 characters from the above format which is in the format “yyyy-mm-dd“.

Example program on how to generate a random date between two dates.

function getRandomDate(startDate, endDate) {
  const timeDiff = endDate.getTime() - startDate.getTime();
  const randomTime = Math.random() * timeDiff;
  const randomDate = new Date(startDate.getTime() + randomTime);
  return randomDate.toISOString().slice(0, 10);
}

const startDate = new Date('2022-01-01');
const endDate = new Date('2022-12-31');
const randomDate = getRandomDate(startDate, endDate);
console.log(randomDate);

Categorized in:

Tagged in: