I want to generate a random date between two dates and between two times in javascript. For instance I want to generate a random date (between 8 am and 6 pm) between today a
Try this:
function getRandomDate(from, to) {
from = from.getTime();
to = to.getTime();
return new Date(from + Math.random() * (to - from));
}
When creating a date you can set a time also:
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
If you want the date to be, for example, between 8 am and 6 pm, simply set a random time after you get a random date.
So in this case the function would look like this:
function getRandomDate(fromDate, toDate, fromTime, toTime) {
fromDate = fromDate.getTime();
toDate = toDate.getTime();
fromTime.setFullYear(1970,0,1); //reset the date
toTime.setFullYear(1970,0,1); //because we only want a time here
fromTime = fromTime.getTime();
toTime = toTime.getTime();
randomDate = new Date(fromDate + Math.random() * (toDate - fromDate));
randomTime = new Date(fromTime + Math.random() * (toTime - fromTime));
randomDate.setHours(randomTime.getHours());
randomDate.setMinutes(randomTime.getMinutes());
randomDate.setSeconds(randomTime.getSeconds());
}