Search code examples
javascriptdaterandommomentjs

Generating random dates between start date and end date in utc format using javascript


How can i generate random dates between two dates in utc format using javascript? example: start date is 23-01-25 02:07:04 and end date is 23-02-25 02:07:04 I want a list of random dates between start date & end date as below: [23-01-26 02:07:04,23-02-02 02:07:04,.....]

This is my Javasxript code:

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

const d = randomDate(new Date(2023, 04, 01), new Date(2023, 04, 12));
console.log(d);

But it gives wrong output:

2023-05-08T17:09:26.445Z

Can anyone suggest me a proper way to get solution


Solution

  • As others have mentioned, months in JavaScript are indexed from 0-11.

    See: Date.prototype.setMonth()

    monthValue
    An integer representing the month: 0 for January, 1 for February, and so on.

    const
      startDate = new Date(2023, 4, 1), // 2023-05-01
      endDate = new Date(2023, 4, 12);  // 2023-05-12
    
    // Generate 1 million random dates between the provided range...
    for (let i = 0; i < 1_000_000; i++) {
      const randomDate = getRandomDate(startDate, endDate);
      if (randomDate < startDate || startDate > endDate) {
        throw new Error(`Date out of range: ${randomDate}`);
      }
    }
    
    // Should get here if there are no range errors...
    console.log('No errors...');
    
    function getRandomDate(startDate, endDate) {
      if (arguments.length === 1) {
        endDate = new Date(startDate.getTime());
        startDate = new Date();
      }
      return new Date(getRandomInt(startDate.getTime(), endDate.getTime()));
    }
    
    function getRandomInt(min, max) {
      if (arguments.length === 1) {
        max = min;
        min = 0;
      }
      return Math.floor(Math.random() * (max - min + 1)) + min;
    }