根据时间间隔构建数组时间

时间:2016-07-23 01:29:11

标签: javascript momentjs

我通过API收到两个日期。我需要根据间隔构建一个可用小时数组。

我收到的这两次都是mm/dd/yyy h:mm:ss a格式,并且我将它们转换为h:mm a(我实际上可以在渲染选择字段时执行此操作我将填充)。

到目前为止我的代码:

let start = moment(location.availableFrom, "MM-DD-YYYY h:mm:ss a");

let end = moment(location.availableTill, 'MM-DD-YYYY h:mm:ss a');

if(start.format('mm') < 30) {
    start = start.format('h:30 a');
} else {
    start = start.add(1, 'h').format('h:00 a');
}

if(end.format('mm') > 30) {
    end = end.format('h:30 a');
} else {
    end = end.format('h:00 a');
}  

是的,我知道这很糟糕。我需要把他们最早的时间从30到30分钟,所以如果我得到晚上8点02分,我需要在晚上8点完成。无论如何,正如我所说,我可以在渲染选择字段时执行此操作。

问题是:如何使用所有可用时间填充数组?又如何创建一个30到30分钟间隔的数组。

感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

试试这个,

&#13;
&#13;
// Code goes here

window.onload = function(){
  
var start = moment('08-02-2013 08:02 pm', "MM-DD-YYYY h:mm:ss a");

var end = moment('08-02-2013 10:21 am', 'MM-DD-YYYY h:mm:ss a');
console.log('start time:'+start.format('hh:mm a')+',end time:'+end.format('hh:mm a'));
var arr = [];
var firstItem = (start.minutes()<=30)?(30-start.minutes()):(60-start.minutes());
var f1 = start.add(firstItem,'minutes');
arr.push(f1.format('hh:mm a'));
for(var i=0;i<48;i++){
  if((f1.format('hh'))==(end.format('hh'))&& ((f1.format('a'))==(end.format('a')))){
    //arr.pop();
    break;
  }
  else{
    f1 = f1.add('30','minutes');
    arr.push(f1.format('hh:mm a'));
  }
}

console.log(arr);
}
&#13;
<head>
    <script data-require="moment.js@*" data-semver="2.14.1" src="https://npmcdn.com/moment@2.14.1"></script>
    <link href="style.css" rel="stylesheet" />
    <script src="script.js"></script>
  </head>

  <body>
    <h1>Time array</h1>
  </body>
&#13;
&#13;
&#13;

测试一下,请告诉我您需要的任何更改或发现的任何问题。