休息时间为30分钟

时间:2016-01-28 05:43:50

标签: javascript date datetime momentjs

我有两个日期开始和结束

"start" : "Wed Jan 27 2016 21:00:00 GMT-0500",
"end" : "Thu Jan 27 2016 23:30:00 GMT-0500"

我想把这个时间划分为像

这样的块
"start" : "Wed Jan 27 2016 21:00:00 GMT-0500",
"end" : "Thu Jan 27 2016 21:30:00 GMT-0500"
----------------------------------------------
"start" : "Wed Jan 27 2016 21:30:00 GMT-0500",
"end" : "Thu Jan 27 2016 22:00:00 GMT-0500"
----------------------------------------------
"start" : "Wed Jan 27 2016 22:00:00 GMT-0500",
"end" : "Thu Jan 27 2016 22:30:00 GMT-0500"
----------------------------------------------
"start" : "Wed Jan 27 2016 22:30:00 GMT-0500",
"end" : "Thu Jan 27 2016 23:00:00 GMT-0500"
----------------------------------------------
"start" : "Wed Jan 27 2016 23:00:00 GMT-0500",
"end" : "Thu Jan 27 2016 23:30:00 GMT-0500"

无论如何使用moment.js或javascript进行此操作?

3 个答案:

答案 0 :(得分:2)

我们可以将时间分成这样的块:



 var time = {
   "start": "Wed Jan 27 2016 21:00:00 GMT-0500",
   "end": "Thu Jan 27 2016 23:30:00 GMT-0500"
 };


 var startTime = new Date(time.start).getTime();
 var endTime = new Date(time.end).getTime();

 var diff = endTime - startTime;

 var chunks = [];
 var hold = startTime;
 var threshold = (60 * 30 * 1000); //30minutes
 for (var i = (startTime + threshold); i <= endTime; i += (threshold)) {
   var newEndTime = new Date(i);
   chunks.push({
     start: new Date(hold),
     end: newEndTime
   });
   hold = newEndTime;
 }
 console.log(chunks)
&#13;
&#13;
&#13;

答案 1 :(得分:2)

使用moment-timezone(假设您为added the timezone),这会将您的间隔写入console.log;

var start = moment.tz('2016-01-27 21:00', 'America/New_York');
var end   = moment.tz('2016-01-27 23:30', 'America/New_York');

while(start < end) {
  console.log('Start: ' + start.format());
  start = start.add(30, 'minutes')
  console.log('End:   ' + start.format());
  console.log();
}

Start: 2016-01-27T21:00:00-05:00
End:   2016-01-27T21:30:00-05:00

Start: 2016-01-27T21:30:00-05:00
End:   2016-01-27T22:00:00-05:00

Start: 2016-01-27T22:00:00-05:00
End:   2016-01-27T22:30:00-05:00

Start: 2016-01-27T22:30:00-05:00
End:   2016-01-27T23:00:00-05:00

Start: 2016-01-27T23:00:00-05:00
End:   2016-01-27T23:30:00-05:00

答案 2 :(得分:1)

var startTime = new Date(start).getTime();
var endTime = new Date(end).getTime();

var duration = 1000 * 60 * 30;
var times = [] ;
var arr_len = (startTime - endTime)/duration;

for(i=0; i< arr_len; i++){
    times.push(new Date(startTime + duration));
}

然后你得到这些块