将字符串数组转换为日期,对其进行过滤并转换回字符串

Convert string array to date, filter it and convert back to string

这可能是一个新手javascript问题,但我对日期很着迷...

我有这个 array 字符串和两个字符串 fromto:

var arr = ['2015-01-20','2015-02-14','2015-02-17','2015-03-06']

var from = '2015-02-01';
var to   = '2015-03-01';

我要获取:

['2015-02-14','2015-02-17']

我尝试使用 underscore.jsmomentjs 但失败了:

_.filter(arr, function(x){
    return moment(x,'YYYY-MM-DD').isBetween(moment(from,'YYYY-MM-DD'), moment(to,'YYYY-MM-DD'))
});

给出空结果 [] ... 我该如何解决这个问题以及获得所需结果的更简洁的方法是什么?

filter 数组,然后使用 moment 的 inBetween 函数。

arr.filter(function(date) {
    return moment(date).isBetween(from,to);
});

来源:http://momentjs.com/docs/#/query/is-between/

查看 the docs,该方法将只接受该格式的字符串(无需创建 moment 对象)。

你还有一个错字,在 from 和 from 之间。 (需要从和到)

arr.filter(function(x) {
    return moment(x).isBetween(from, to);
});