126

I have a datepicker where I show two months and I want to randomly choose 3 dates in each visible month

  $('.date').datepicker({
    minDate: new Date(),
    dateFormat: 'DD, MM, d, yy',
    constrainInput: true,
    beforeShowDay: processDates,
    numberOfMonths: 2,
    showButtonPanel: true,
    showOn: "button",
    buttonImage: "images/calendar_icon.jpg",
    buttonImageOnly: true    
  });

Here is my calculation

var now = new Date();
var nowTime = parseInt(now.getTime()/1000);
var randomDateSet = {};

function getRandomSet(y,m) {
  var monthIndex = "m"+y+""+m; // m20121 for Jan
  if (randomDateSet[monthIndex]) return randomDateSet[monthIndex];
  // generate here
.
. - I need this part
.
  return randomDateSet[monthIndex];
}

function processDay(date) { // this is calculated for each day so we need a singleton for the array
  var dateTime = parseInt(date.getTime()/1000);
  if (dateTime <= (nowTime-86400)) {
    return [false]; // earlier than today
  }
  var m = date.getMonth(), d = date.getDate(), y = date.getFullYear();
  var randomDates = getRandomSet(y,m);

  for (i = 0; i < randomDates.length; i++) {
    if($.inArray((m+1) + '-' + d + '-' + y,randomDates) != -1 || new Date() > date) {
      return [true,"highlight","Some message"];
    }
  }
  return [true,"normal"]; // ordinary day
}
0

7 Answers 7

340

Maybe I am missing something, but isn't this it?

function randomDate(start, end) {
  return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
}

const d = randomDate(new Date(2012, 0, 1), new Date());
console.log(d);

4
  • 1
    Perhaps - can you do that for 3 dates without overlap in each month?
    – mplungjan
    Commented Jan 27, 2012 at 15:46
  • 1
    By overlaps do you mean generating the same date? No, this code does not handle this case, theoretically it can generate the same date (especially when you truncate time). But it shouldn't be hard to get rid of duplicates. Commented Jan 27, 2012 at 15:50
  • 3
    Related function for getting a date a number of days before (or after) the given date: function randomDateAfterDate(start, days) { return new Date(start.getTime() + (Math.random()*days*24*60*60*1000)); } Commented Nov 17, 2015 at 15:29
  • to test @AutumnLeonard example for the case when we need the number of days before the given date we can use minus sign - randomDateAfterDate(new Date(2021, 4, 5), -365)
    – SAndriy
    Commented May 5, 2021 at 10:22
63

console.log(
  new Date(new Date() - Math.random()*(1e+12))
)

1
  • 3
    @Typescript users: new Date(new Date().valueOf() - Math.random()*(1e+12)) Commented Jun 9, 2023 at 13:53
13

Using Moment.js && @Demven Weir's answer to get a string value like "03/02/1975".

moment(new Date(+(new Date()) - Math.floor(Math.random()*10000000000)))
.format('MM/DD/YYYY');

NOTE: Keep adding a zero at a time to increase the span of years produced.

1
  • This adds nothing to the question. You're adding formatting that nobody asked for. Commented Jun 9, 2023 at 13:55
3
function generateRandomDate() {
return new Date(+(new Date()) - Math.floor(Math.random() * 10000000000));
}

(new generateRandomDate()).toLocaleDateString('en-US')

You will get a random date in US format 4/25/2021

See this Demo on jsfiddle

1
  • This adds nothing to the question. You're adding formatting that nobody asked for. Commented Jun 9, 2023 at 13:54
2

You can convert the boundary dates to integers (Date.getTime()) and then use Math.random() to generate your random dates within given boundaries. Then go back to Date objects with Date.setTime().

2
  • x times without repeat (here x=3) ?
    – mplungjan
    Commented Jan 27, 2012 at 15:45
  • A matter of adding a loop and an array of already generated dates to check against when generating new one. Or am I missing something?
    – bububaba
    Commented Jan 27, 2012 at 15:48
2

You can use this snippet to get random date and format;

const emptyDate = new Date();
const randomDate = new Date();
const dateFormatter = Intl.DateTimeFormat('sv-SE');
const formattedRandomDate = dateFormatter.format(emptyDate.setDate(randomDate.getDate() - Math.floor(Math.random()*1000)));
2

From examples in date-fns

const result = eachDayOfInterval({
  start: new Date(2014, 9, 6),
  end: new Date(2014, 9, 10)
})

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.