Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

javascript - JS / TypeScript生成小时之间的时间(JS/TypeScript Generate times between hours)

So let's say we have two times:(假设我们有两次:)

7:30 - 12:00(7:30-12:00)

So my question is how can I generate an array with times like this:(所以我的问题是如何生成具有以下时间的数组:)

7:30, 8:00, 8:30, 9:00, 9:30, 10:00, 10:30, 11:00, 11:30(7:30、8:00、8:30、9:00、9:30、10:00、10:30、11:00、11:30)

I need this for a booking, so let's say the business will open at 7:30 and every booking that you can make will be 30 min(this time can change, could be one hour or more)(我需要这个来进行预订,所以说,该公司将在7:30开放,您可以进行的每次预订都将是30分钟(此时间可以更改,可能是一小时或更长时间))

Whats the best way to generate something like this in JS?(在JS中生成这样的东西的最佳方法是什么?)

  ask by Uffo translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Little verbose utility, you can use it..(有点冗长的实用程序,您可以使用它。)

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"));

Function getTimeIntervals expects startDate , endDate , slotDurationInMinutes , workingHoursStart and workingHourEnd .(函数getTimeIntervals期望startDateendDateslotDurationInMinutesworkingHoursStartworkingHourEnd 。)

Why I am returning object is because you may need the timestamp of selected slot in your further application use.(我之所以返回对象,是因为您可能需要在以后的应用程序使用中选择插槽的时间戳。)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...