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
2
Answers
As others have mentioned, months in JavaScript are indexed from 0-11.
See:
Date.prototype.setMonth()
Perhaps you should convert the dates to the time format and calculate a random number in the range of two numbers.