Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
360 views
in Technique[技术] by (71.8m points)

javascript - Elegant method to generate array of random dates within two dates

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
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...