问题
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
}
回答1:
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()));
}
randomDate(new Date(2012, 0, 1), new Date())
回答2:
new Date(+(new Date()) - Math.floor(Math.random()*10000000000))
回答3:
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.
回答4:
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()
.
来源:https://stackoverflow.com/questions/9035627/elegant-method-to-generate-array-of-random-dates-within-two-dates