在两个date内生成随机date数组的优雅方法

我有一个dateselect器,显示两个月,我想在每个可见的月份随机select3个date

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

这是我的计算

 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 } 

也许我错过了一些东西,但不是这样吗?

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

您可以将边界date转换为整数( Date.getTime() ),然后使用Math.random()在给定边界内生成随机date。 然后用Date.setTime()返回Date对象。

 new Date(+(new Date()) - Math.floor(Math.random()*10000000000))