Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random date between two dates and times in Javascript

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

like image 807
Yanki Twizzy Avatar asked Jul 13 '15 08:07

Yanki Twizzy


2 Answers

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; } 
like image 147
Peter Olson Avatar answered Oct 20 '22 11:10

Peter Olson


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" 
like image 39
Barrard Avatar answered Oct 20 '22 11:10

Barrard