40

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

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
Yanki Twizzy
  • 7,771
  • 8
  • 41
  • 68
  • 1
    You should still post the code that didn't work, so we can start somewhere. – doldt Jul 13 '15 at 08:22
  • 1
    Looks like you simply need to [generate two random numbers in specific ranges](http://stackoverflow.com/q/1527803/218196). Did you try that already? – Felix Kling Jul 13 '15 at 08:23
  • 2
    Try this: http://stackoverflow.com/questions/9035627/elegant-method-to-generate-array-of-random-dates-within-two-dates – Oliver Gray Jul 13 '15 at 08:26
  • What you have there should theoretically work. Could you explain why it's wrong? – Ja͢ck Jul 13 '15 at 08: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 – Yanki Twizzy Jul 13 '15 at 08:31
  • @Ja͢ck It's correct if I am just generating a random date between two dates. I want to generate a random date between two dates that falls between certain times not just any time – Yanki Twizzy Jul 13 '15 at 08:33
  • Sure, ideally you could just take two timestamps and get a random value in between. But you have additional constraints. I could image that the random date function accepts a callback which validates the random date, and keeps generating random dates until the callback returns `true`. But the code might never terminate. – Felix Kling Jul 13 '15 at 08:33
  • @FelixKling Exactly. This code would be used on a mobile app so I don't want to have code that "does not terminate" – Yanki Twizzy Jul 13 '15 at 08:38
  • Which browser do you use? – benams Jul 13 '15 at 08:44
  • @benams It doesn't matter what browser. Does it? – Yanki Twizzy Jul 13 '15 at 08:46

8 Answers8

48

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;
}
Peter Olson
  • 139,199
  • 49
  • 202
  • 242
  • 3
    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. – dmikester1 Jan 07 '20 at 20:53
  • type Javascript Date - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date – Piper0804 May 29 '20 at 23:07
  • 2
    E.g. `randomDate(new Date(2020, 0, 1), new Date(), 0, 24)` – Ryan Allen Oct 13 '20 at 19:55
  • Sorry I know this is a very late response but recently I created this library @fars20/random-sources https://www.npmjs.com/package/@fars20/random-sources to do that – Sagar Oct 25 '20 at 18:27
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"
Barrard
  • 1,783
  • 1
  • 18
  • 25
10

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));
}
Oliver Dixon
  • 7,012
  • 5
  • 61
  • 95
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());
}
user1136881
  • 182
  • 1
  • 6
  • 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. – Yanki Twizzy Jul 13 '15 at 08:37
  • @YankiTwizzy I don't understand, his function returns random `Date`s between `from` and `to`, isn't that what you want? – Peter Olson Jul 13 '15 at 08:39
  • @YankiTwizzy I updated the answer, you can specify the time when you creating a date. – user1136881 Jul 13 '15 at 08:40
  • @user1136881 Your solution is generating random dates between two dates not random dates between two dates and two times (which is what I want) – Yanki Twizzy Jul 13 '15 at 08:44
  • @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. – user1136881 Jul 13 '15 at 08:46
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.

Pravin
  • 1,671
  • 5
  • 23
  • 36
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;
}
benams
  • 4,308
  • 9
  • 32
  • 74
  • 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 `Date`s. – Peter Olson Jul 13 '15 at 08:40
  • @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. – Yanki Twizzy Jul 13 '15 at 08:43
  • please visit the jsfiddle link I attached. you can find there 2 specific dates. – benams Jul 13 '15 at 08:45
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(); 
} 
M_0090
  • 31
  • 7
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'));
Puerto AGP
  • 393
  • 5
  • 11