最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

datetime - JavaScript split time in chunks - Stack Overflow

programmeradmin0浏览0评论

How could I split time every X minutes, if I know the start time and end time. So for instance, if my start time is 13:00 and my end time is: 15:00 and splitting it every 30 minutes, then I would like to get an array containing:

13:00 - 13:30
14:00 - 14:30
14:30 - 15:00

How could I split time every X minutes, if I know the start time and end time. So for instance, if my start time is 13:00 and my end time is: 15:00 and splitting it every 30 minutes, then I would like to get an array containing:

13:00 - 13:30
14:00 - 14:30
14:30 - 15:00
Share Improve this question asked Aug 9, 2011 at 16:01 Mike HollandMike Holland 311 silver badge2 bronze badges 3
  • what variable type are your times stored in? Strings? – Spycho Commented Aug 9, 2011 at 16:04
  • What should the output array contain? Those strings, literally? Or pairs of Date objects? Something else? – Wayne Commented Aug 9, 2011 at 17:30
  • either way... preferably the Date Object – Mike Holland Commented Aug 9, 2011 at 18:57
Add a ment  | 

4 Answers 4

Reset to default 1
13:00 - 13:30
13:30 - 14:00
14:00 - 14:30
14:30 - 15:00

see it in action

var makeTimeIntervals = function (startTime, endTime, increment) {
    startTime = startTime.toString().split(':');
    endTime = endTime.toString().split(':');
    increment = parseInt(increment, 10);

    var pad = function (n) { return (n < 10) ? '0' + n.toString() : n; },
        startHr = parseInt(startTime[0], 10),
        startMin = parseInt(startTime[1], 10),
        endHr = parseInt(endTime[0], 10),
        endMin = parseInt(endTime[1], 10),
        currentHr = startHr,
        currentMin = startMin,
        previous = currentHr + ':' + pad(currentMin),
        current = '',
        r = [];

    do {
        currentMin += increment;
        if ((currentMin % 60) === 0 || currentMin > 60) {
            currentMin = (currentMin === 60) ? 0 : currentMin - 60;
            currentHr += 1;
        }
        current = currentHr + ':' + pad(currentMin);
        r.push(previous + ' - ' + current);
        previous = current;
  } while (currentHr !== endHr);

    return r;
};

var a = makeTimeIntervals('13:00', '15:00', 30);

for (var i in a) if (a.hasOwnProperty(i)) { document.body.innerHTML += a[i] + '<br />'; }

You can use datejs and its add method to add minutes to your Date object. The pareTo method can be used to check that you are still within the appropriate range.

If you don't want to use an external library, you can refer to W3Schools.

// Set minutes.
var myDate = new Date();
myDate.setMinutes(myDate.getMinutes() + 30);

// Compare two dates.
var x = new Date();
x.setFullYear(2100, 0, 14);
var today = new Date();
if (x > today) {
    alert("Today is before 14th January 2100");
} else {
    alert("Today is after 14th January 2100");
}

well that wrecks everything :P ... oh well ... for this who want to do this for strings:

function getIntervals(startString,endString,intervalString) {
var start = startString.split(":");
var end = endString.split(":");
var interval = intervalString.split(":");
startInMinutes = start[0]*60+start[1]*1;
endInMinutes = end[0]*60+end[1]*1;
intervalInMinutes = interval[0]*60+interval[1]*1;
var times = [];
var intervalsOfTime = [];

for(var i = startInMinutes; i <= endInMinutes; i+=intervalInMinutes) {
  var hour = Math.floor(i/60) + "";
  var minute = i%60 + "";
  minute = (minute.length < 2) ? "0" + minute : minute;
  hour = (hour.length < 2) ? "0" + hour : hour;
  times.push( hour + ":" + minute);
}


for(var i = 0; i < times.length-1; i++)
  intervalsOfTime.push(times[i] + " - " + times[i+1])

return intervalsOfTime;

}

I know I'm late in answering this, but I'm posting my solution for anybody who's still stuck.

Using moment.js:-

const moment = require('moment');

// Actual logic

const splitTime = (startTime, endTime, interval) =>{
    const result = [startTime.toString()];
    let time = startTime.add(interval,'m');
    while(time.isBetween(startTime,endTime,undefined,[])){
        result.push(time.toString());
        time = time.add(interval,'m');
    }
    return result;
}


// You change these values according to your needs

const interval = 60;
const startTime = new moment({hour:00,minute:00});
const endTime = new moment({hour:12, minute:00});

const timeSlices = splitTime(startTime,endTime,interval); 

// For printing out the intervals 

for(let i=0;i<timeSlices.length-1;i++){
    console.log(timeSlices[i]+" - "+timeSlices[i+1]);
}

Hope this was a straightforward answer and has helped you, reader. :)

发布评论

评论列表(0)

  1. 暂无评论