Javascript 在两个日期内生成随机日期数组的优雅方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9035627/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 08:26:47  来源:igfitidea点击:

Elegant method to generate array of random dates within two dates

javascriptdaterandomjquery-ui-datepicker

提问by mplungjan

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

我有一个显示两个月的日期选择器,我想在每个可见的月份随机选择 3 个日期

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

回答by Tomasz Nurkiewicz

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

回答by Demven Weir

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

回答by SoEzPz

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

使用Moment.js&& @Demven Weir 的答案来获得像“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.

注意:继续一次添加一个零以增加生产年份的跨度。

回答by bububaba

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 Dateobjects with Date.setTime().

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