42

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

10
  • 1
    You should still post the code that didn't work, so we can start somewhere. Commented Jul 13, 2015 at 8:22
  • 1
    Looks like you simply need to generate two random numbers in specific ranges. Did you try that already? Commented Jul 13, 2015 at 8:23
  • 2
    Try this: stackoverflow.com/questions/9035627/… Commented Jul 13, 2015 at 8:26
  • What you have there should theoretically work. Could you explain why it's wrong? Commented Jul 13, 2015 at 8:30
  • @FelixKling Your suggestion sounds interesting but I want something generic I can use. Imagine if I am generating a random date between today and this time next year, it won't be easy to use your approach Commented Jul 13, 2015 at 8:31

8 Answers 8

51

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;
}
Sign up to request clarification or add additional context in comments.

4 Comments

And what should start and end be? I tried it passing random integers and it always returns Wed Dec 31 1969 but a different time every time I change the start and end.
E.g. randomDate(new Date(2020, 0, 1), new Date(), 0, 24)
Sorry I know this is a very late response but recently I created this library @fars20/random-sources npmjs.com/package/@fars20/random-sources to do that
14

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

Comments

11

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"

Comments

3

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

5 Comments

There is no difference between your solution and my code. I want to generate random dates that fall between certain times not just any time.
@YankiTwizzy I don't understand, his function returns random Dates between from and to, isn't that what you want?
@YankiTwizzy I updated the answer, you can specify the time when you creating a date.
@user1136881 Your solution is generating random dates between two dates not random dates between two dates and two times (which is what I want)
@YankiTwizzy 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.
3

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.

1 Comment

getMonth is 0-based, so you need to be adding 1 to it.
1

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

3 Comments

You can also use +end and +start instead of end.getTime() and start.getTime(), and it allows you to pass in numbers as well as Dates.
@benams There is no difference between your solution and my code. I want to generate random dates that fall between certain times not just any time.
please visit the jsfiddle link I attached. you can find there 2 specific dates.
1

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.