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
Since everyone is doing TypeScript now. Here's a more modern example with an example of how to use it.
const generateRandomDOB = (): string => {
const random = getRandomDate(new Date('1950-02-12T01:57:45.271Z'), new Date('2001-02-12T01:57:45.271Z'))
return random.toISOString();
}
function getRandomDate(from: Date, to: Date) {
const fromTime = from.getTime();
const toTime = to.getTime();
return new Date(fromTime + Math.random() * (toTime - fromTime));
}
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;
}
A single function.
function (line) {
return new Date(new Date('2019-02-12T01:57:45.271Z').getTime() + Math.random() * (new Date('2020-02-12T01:57:45.271Z').getTime() - new Date('2019-02-12T01:57:45.271Z').getTime())).toISOString();
}
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());
}
You can use JS ability to convert a Date to an integer timestamp
Here is a simple working JSfiddle:
function randomTime(start, end) {
var diff = end.getTime() - start.getTime();
var new_diff = diff * Math.random();
var date = new Date(start.getTime() + new_diff);
return date;
}
try this:
var yourRandomGenerator=function(rangeOfDays,startHour,hourRange){
var today = new Date(Date.now());
return new Date(today.getYear()+1900,today.getMonth(), today.getDate()+Math.random() *rangeOfDays, Math.random()*hourRange + startHour, Math.random()*60)
}
console.log(yourRandomGenerator(2,8,2));
here's a working fiddle.