Generate random date between two dates and times in Javascript
I think I understand what you are after. This will return a random date between start
and end
, with a random hour between startHour
and endHour
(which should be values in the range 0-23
).
function randomDate(start, end, startHour, endHour) {
var date = new Date(+start + Math.random() * (end - start));
var hour = startHour + Math.random() * (endHour - startHour) | 0;
date.setHours(hour);
return date;
}
Here is a good one if you just want simple dates such as: ('12/13/2013', '01/26/2011')
function randomDate(date1, date2){
function randomValueBetween(min, max) {
return Math.random() * (max - min) + min;
}
var date1 = date1 || '01-01-1970'
var date2 = date2 || new Date().toLocaleDateString()
date1 = new Date(date1).getTime()
date2 = new Date(date2).getTime()
if( date1>date2){
return new Date(randomValueBetween(date2,date1)).toLocaleDateString()
} else{
return new Date(randomValueBetween(date1, date2)).toLocaleDateString()
}
}
randomDate('02/13/2013', '01/01/2000')
"1/31/2009"
randomDate()
"6/14/2001"