我正在使用Angular 5中的moment.js。
我有这样的数组:
public lineChartLabels: Array<any> = [ "2018/26/02 10:01:00", "2018/26/02 10:02:00", "2018/26/02 10:03:00", "2018/26/02 10:04:00", "2018/26/02 10:05:00", "2018/26/02 10:06:00", "2018/26/02 10:07:00", "2018/26/02 10:08:00", "2018/26/02 10:09:00", "2018/26/02 10:10:00", "2018/26/02 10:11:00", "2018/26/02 10:12:00","2018/26/02 10:13:00", "2018/26/02 10:14:00", "2018/26/02 10:15:00" ];
我有timeStart;
和timeEnd;
。我只是先报告,我以同样的方式初始化
let timeStart = moment();
timeStart.format('YYYY/MM/DD HH:mm:ss');
timeStart.year(2018);
timeStart.month(2);
timeStart.date(26);
timeStart.hour(10);
timeStart.minute(10);
timeStart.second(0);
timeEnd
我使用timeStart.hour(10); timeStart.minute(13);
现在我必须实施这个循环:
for( let i = 0; i < this.lineChartLabels.length; i++ ){
if (moment(this.lineChartsLabels[i]).isBetween(timeStart, timeEnd) ) {
console.log ( 'true' );
}
else {
console.log ( 'false' );
}
}
但它不起作用。
你知道我该如何解决?
答案 0 :(得分:2)
您的代码有两个问题:
moment(String)
(ISO 8601或RFC 2822)无法识别lineChartLabels
值,因此您必须使用moment(String, String)
传递格式作为第二个参数({{1}在你的情况下) JavaScript月份已编入索引,因此month()
:
获取或设置月份。
接受0到11之间的数字。如果超出范围,它将会冒泡到年份。
您的'YYYY/DD/MM HH:mm:ss'
和timeStart
代表3月26日
这是一个实时样本:
timeEnd
&#13;
const lineChartLabels = [ "2018/26/02 10:01:00", "2018/26/02 10:02:00", "2018/26/02 10:03:00", "2018/26/02 10:04:00", "2018/26/02 10:05:00", "2018/26/02 10:06:00", "2018/26/02 10:07:00", "2018/26/02 10:08:00", "2018/26/02 10:09:00", "2018/26/02 10:10:00", "2018/26/02 10:11:00", "2018/26/02 10:12:00","2018/26/02 10:13:00", "2018/26/02 10:14:00", "2018/26/02 10:15:00" ];
let timeStart = moment();
timeStart.year(2018);
timeStart.month(2-1); // Months are 0 index, 2 stands for March
timeStart.date(26);
timeStart.hour(10);
timeStart.minute(10);
timeStart.second(0);
let timeEnd = moment(timeStart).hour(10).minute(13);
console.log(timeStart.format());
console.log(timeEnd.format());
for( let i = 0; i < lineChartLabels.length; i++ ){
if (moment(lineChartLabels[i], 'YYYY/DD/MM HH:mm:ss').isBetween(timeStart, timeEnd) ) {
console.log ( 'true' );
}
else {
console.log ( 'false' );
}
}
&#13;