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 and next tomorrow. I have tried a whole bunch of things but none of them work so I won't be pasting any code since it does not work. Has anyone done something similar
function generateRandomDate(start, end) { return new Date(start + Math.random() * (end - start)); }
The code I am using for generating random dates is posted above
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With