简体   繁体   中英

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

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;
}

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));
}

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"

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());
}

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 'sa working fiddle.

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;
}

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(); 
} 

If you don't mind being limited to dates from 1970-01-01 00:00:00 on, this might work for you:

 function getRamdomDateInBetween(start, end) { start = Date.parse(start); end = Date.parse(end); return new Date(Math.floor(Math.random() * (end - start + 1) + start)); } console.log(getRamdomDateInBetween('2021-01-01', '2021-01-30'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM