Categories
JavaScript Answers

How to generate array of random dates within two dates with JavaScript?

Spread the love

Sometimes, we want to generate array of random dates within two dates with JavaScript.

In this article, we’ll look at how to generate array of random dates within two dates with JavaScript.

How to generate array of random dates within two dates with JavaScript?

To generate array of random dates within two dates with JavaScript, we can use the Math.random method.

For instance, we write

const randomDate = (start, end) => {
  return new Date(
    start.getTime() + Math.random() * (end.getTime() - start.getTime())
  );
};

const d = randomDate(new Date(2012, 0, 1), new Date());
console.log(d);

to define the randomDate function that takes the start and end dates.

We get the timestamp in between start and end with

start.getTime() + Math.random() * (end.getTime() - start.getTime())

Math.random returns a number between 0 and 1, so we multiply the returned number with (end.getTime() - start.getTime()) and add start.getTime to get a timestamp in milliseconds between start and end and use that as the argument of Date to get a new Date object with the timestamp.

Conclusion

To generate array of random dates within two dates with JavaScript, we can use the Math.random method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *