JS / TypeScript生成几小时之间的时间

时间:2017-07-30 12:53:49

标签: javascript angular typescript

所以我们说我们有两次:

  

7:30 - 12:00

所以我的问题是如何在这样的时间生成一个数组:

  

7:30,8:00,8:30,9:00,9:30,10:00,10:30,11:00,11:30

我需要这个用于预订,所以让我们说业务将在7:30开始,你可以做的每个预订都是30分钟(这个时间可以改变,可能是一个小时或更长)< / p>

什么是在JS中生成类似内容的最佳方法?

3 个答案:

答案 0 :(得分:1)

小冗长的实用程序,你可以使用它..

var getTimeIntervals = function (time1, time2, slotInMinutes, workingHourStart, workingHourEnd) {
    time1.setMinutes(0); time1.setSeconds(0);
    var arr = [];
    var workingHoursStart = workingHourStart;
    var workingHourEnds = workingHourEnd;
    var workingHourStartFloat = parseFloat("7:30");
    var workingHourEndFloat = parseFloat("12:00");
    while(time1 < time2){
      var generatedSlot = time1.toTimeString().substring(0,5);
      var generatedSlotFloat = parseFloat(generatedSlot);

      time1.setMinutes(time1.getMinutes() + slotInMinutes);
      if(generatedSlotFloat >= workingHourStartFloat && generatedSlotFloat < workingHourEndFloat){
          var generatedObject = {
            slot: time1.toTimeString().substring(0,5),
            timeStamp: new Date(time1.getTime())
          };
          arr.push(generatedObject);
      }
    }
   return arr;
 }

var today = new Date();
var tomrorow = new Date().setDate(today.getDate()+1);

console.log(getTimeIntervals(today, tomorrow, 30, "7:30", "12:00"));

功能getTimeIntervals需要startDateendDateslotDurationInMinutesworkingHoursStartworkingHourEnd

为什么我要返回对象是因为您可能需要在进一步的应用程序中使用所选插槽的时间戳。

小提琴 - https://jsfiddle.net/rahulrulez/t8ezfj2q/

答案 1 :(得分:1)

较短的版本:

    timeArray = [];
....
    let i = 7;
    let hour = 7;
    let odd:boolean;
    do {
        odd = false;
        if (i % 2 === 0) {
            odd = true;
            hour = hour - 1;
        }
        this.timeArray.push(hour.toString() + (odd ? ":30" : ""));
        i = i + 1;
        hour = hour + 1;
    } while (i < 36)

plunker

答案 2 :(得分:0)

正如代码中的注释所示,如果您不想要它,可以通过删除该行来删除小时之前的0。

如果您不希望数组中的结尾只是在for循环中将<=替换为<

function timeArray(start, end){
    var start = start.split(":");
    var end = end.split(":");

    start = parseInt(start[0]) * 60 + parseInt(start[1]);
    end = parseInt(end[0]) * 60 + parseInt(end[1]);

    var result = [];

    for ( time = start; time <= end; time+=30){
        result.push( timeString(time));
    }
	
    return result;
}

function timeString(time){
    var hours = Math.floor(time / 60);
    var minutes = time % 60;

    if (hours < 10) hours = "0" + hours; //optional
    if (minutes < 10) minutes = "0" + minutes;

    return hours + ":" + minutes;
}

console.log(timeArray("7:30", "12:00"));