2012-01-27 48 views
50

我有一個日期選擇器,我展示兩個月,我想隨機選擇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  
    }); 

這裏內生成隨機日期的陣列是我的計算

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 
} 

回答

158

也許我錯過了一些東西,但不是這樣嗎?

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

randomDate(new Date(2012, 0, 1), new Date()) 
+1

也許 - 你可以做3個日期,每個月沒有重疊嗎? – mplungjan 2012-01-27 15:46:12

+0

By * overlaps *你的意思是生成同一日期嗎?不,這個代碼不處理這種情況,理論上它可以生成相同的日期(特別是當你截斷時間時)。但要擺脫重複,不應該很難。 – 2012-01-27 15:50:41

+2

相關函數獲取給定日期之前(或之後)天數的日期: 'function randomDateAfterDate(start,days){ return new Date(start.getTime()+(Math.random()* days * 24 * 60 * 60 * 1000)); }' – 2015-11-17 15:29:17

1

您可以將邊界日期轉換爲整數(Date.getTime()),然後使用Math.random()在給定邊界內生成隨機日期。然後回到Date對象Date.setTime()

+0

x次重複無(在此,x = 3)? – mplungjan 2012-01-27 15:45:33

+0

添加一個循環和一個已經生成的日期數組,以便在生成新日期時進行檢查。或者我錯過了什麼? – bububaba 2012-01-27 15:48:17

+0

當然 - 但優雅? – mplungjan 2012-01-27 19:35:22

2
new Date(+(new Date()) - Math.floor(Math.random()*10000000000)) 
相關問題