如何使用Moment.JS检查时间戳是否在两个其他时间戳之间

时间:2017-04-11 08:11:38

标签: javascript arrays json momentjs

我有以下JSON数组(注意这些只是数组的第5和第6个元素):

[   
{ 
    Day: 'Mon',
    EndTime: '{ts \'1970-01-01 18:00:00\'}',
    StartTime: '{ts \'1970-01-01 16:30:00\'}',
    courseName: 'Computer Science 250: Introduction to Website Design',
    Credits: '4' 
},  
{   
    Day: 'Mon',
    EndTime: '{ts \'1970-01-01 18:30:00\'}',
    StartTime: '{ts \'1970-01-01 17:30:00\'}',
    courseName: 'Math 220: Differential Equations',
    Credits: '3' 
}
]

数组中的数据按“EndTime”的值排序。当我尝试检查对象在i - 1(18:00:00)的结束时间是否在下一个对象的开始时间和结束时间之间时(在i,如果是17:30:00到18:30: 00)我应该成为现实,但isBetween方法返回false。

我怎么能解决这个问题,我知道我犯了一些简单的错误?

这是我的代码:

for(let i = 1; i < monday.length-1; i++) {

const year = '1970-01-01';
const format = 'DD/MM/YYYY hh:mm:ss a';

  var next_endtime = monday[i].EndTime.substr(16, 8);
  var next_starttime = monday[i].StartTime.substr(16, 8);
  var prev_endtime = monday[i-1].EndTime.substr(16, 8);

  var plesson_e = moment(year + 'T' + prev_endtime, format), 
      nlesson_start = moment(year + 'T' + next_starttime, format), 
      nlesson_end = moment(year + 'T' + next_endtime, format);

  var testbool = moment(plesson_e).isBetween(nlesson_start, nlesson_end, 'time');

console.log(testbool);
}

2 个答案:

答案 0 :(得分:0)

日期时间或格式有问题,你传递给片刻JS,它对我有用:

&#13;
&#13;
const monday = [{
    Day: 'Mon',
    EndTime: '{ts \'1970-01-01 18:00:00\'}',
    StartTime: '{ts \'1970-01-01 16:30:00\'}',
    courseName: 'Computer Science 250: Introduction to Website Design',
    Credits: '4'
  },
  {
    Day: 'Mon',
    EndTime: '{ts \'1970-01-01 18:30:00\'}',
    StartTime: '{ts \'1970-01-01 17:30:00\'}',
    courseName: 'Math 220: Differential Equations',
    Credits: '3'
  }
]

const format = 'hh:mm:ss a';

var next_endtime = monday[1].EndTime.substr(16, 8);
var next_starttime = monday[1].StartTime.substr(16, 8);
var prev_endtime = monday[0].EndTime.substr(16, 8);

var plesson_e = moment(prev_endtime, format),
  nlesson_start = moment(next_starttime, format),
  nlesson_end = moment(next_endtime, format);

var testbool = moment(plesson_e).isBetween(nlesson_start, nlesson_end, 'time');

console.log(next_endtime, next_starttime, prev_endtime);
console.log(nlesson_end, nlesson_start, plesson_e);
console.log(testbool);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您传递给片刻的字符串与指定的格式不符:

 spl_autoload_register(function ($class) {

 }); //This part here

尝试将格式值更改为:

const year = '1970-01-01'; // => see the '-', and the year is first
const format = 'DD/MM/YYYY hh:mm:ss a'; // => you put '/' and day first

请参阅this fiddle