2015-06-03 53 views
0

我在這裏的邏輯有點困難,它已經越來越晚了,說實話,我很難過。迭代通過時隙

我需要通過時隙循環。

var settings = { 
    startOfWeek:0, //0 = Sunday, 1 = Monday 
    timeSlotGap: 30, 
    minTime: "09:00:00", 
    maxTime: "17:30:00", 
    numSlots: 0 
}; 

因此,我可以指定一個時隙的間隙,因此,如果我是通過時隙(具有30分鐘的間隔)來迭代這將是:

09:00 
09:30 
10:00 
10:30 

目前我有以下內容:

$(document).ready(function() { 

    getNumSlots(settings.minTime, settings.maxTime, settings.timeSlotGap); 

    for(var i = 1; i<=settings.numSlots; i++){ 
     //I have no idea what I'm doing here 
     $('#calendar').append("<p>Timeslot:" + i +"</p>"); 
    } 


}); 
var WeekNo = moment().week(); 
var CurrentDate = getCurrentDate(); 
var WeekDay = moment().weekday(); 



var settings = { 
    startOfWeek:0, //0 = Sunday, 1 = Monday 
    timeSlotGap: 60, 
    minTime: "09:00:00", 
    maxTime: "17:30:00", 
    numSlots: 0 
}; 


if(settings.startOfWeek == 0){ 
    WeekDay = WeekDay - 1; 
} 


function getNumSlots(minTime, maxTime, timeSlotGap){ 
    var minTimeSplit = minTime.split(":"); 
    var hourStart = new Date("01/01/1900 " + minTime).getHours(); 
    var hourEnd = new Date("01/01/1900 " + maxTime).getHours(); 

    var minStart = new Date("01/01/1900 " + minTime).getMinutes(); 
    var minEnd = new Date("01/01/1900 " + maxTime).getMinutes(); 


    var diffHour = hourEnd - hourStart; 
    var diffMins = minEnd - minStart; 

    var slots = ((diffHour * 60) + diffMins)/timeSlotGap; 

    settings.numSlots = slots; 
} 

如果是通過30/60分鐘這不會是一個問題,但因爲我可以指定時間段即,90分鐘任何事情它使一個稍微難循環一樣簡單。

回答

3

爲了讓你可以使用類似下面的時隙:

var settings = { 
    startOfWeek:0, //0 = Sunday, 1 = Monday 
    timeSlotGap: 30, 
    minTime: "09:00:00", 
    maxTime: "17:30:00", 
    numSlots: 0 
}; 

function getTimeDate(time) { 
    var timeParts = time.split(':'); 
    var d = new Date(); 

    d.setHours(timeParts[0]); 
    d.setMinutes(timeParts[1]); 
    d.setSeconds(timeParts[2]); 

    return d; 
} 

function getTimeSlots(startDate, endDate, interval) { 
    var slots = []; 

    var intervalMillis = interval * 60 * 1000; 

    while (startDate < endDate) { 
     // So that you get "00" if we're on the hour. 
     var mins = (startDate.getMinutes() + '0').slice(0, 2); 
     slots.push(startDate.getHours() + ':' + mins); 
     startDate.setTime(startDate.getTime() + intervalMillis); 
    } 

    return slots; 
} 

var slots = getTimeSlots(
    getTimeDate(settings.minTime), getTimeDate(settings.maxTime), settings.timeSlotGap 
); 

下面是一個例子​​。

+0

嗨jabclab,這不是我試圖得到的時間段數。這是時間自己的時間價值,即9點30分,10點10分,10點30分等,如果不明確,則表示抱歉。 –

+0

@Jezzabeanz我的錯誤:)將更新答案 – jabclab

+0

啊,它是完美的。謝謝@ jabclab! –