从数组中筛选日期范围

Filter a range of dates from an array

我正在读取一个 .txt 文件,我已将其拆分为包含信息行的数组。

这是我原来的.txt

|datestamp              |endpoint    |id    |
|2019-03-01 09:00:00UTC |/co.html    |12345 |
|2019-03-01 09:00:00UTC |/co.html    |12346 |
|2019-03-01 10:00:00UTC |/co.html    |12345 |
|2019-03-01 10:30:00UTC |/hello.html |12347 |
|2019-03-01 11:00:00UTC |/co.html    |12347 |
|2019-03-02 11:00:00UTC |/co.html    |12348 |
|2019-03-02 12:00:00UTC |/hello.html |12348 |
|2019-03-03 13:00:00UTC |/hello.html |12349 |

所以现在我得到了这些信息:

[
'|datestamp              |endpoint    |id    |',
'|2019-03-01 09:00:00UTC |/co.html    |12345 |',
'|2019-03-01 09:00:00UTC |/co.html    |12346 |',
'|2019-03-01 10:00:00UTC |/co.html    |12345 |',
'|2019-03-01 10:30:00UTC |/hello.html |12347 |',
'|2019-03-01 11:00:00UTC |/co.html    |12347 |',
'|2019-03-02 11:00:00UTC |/co.html    |12348 |',
'|2019-03-02 12:00:00UTC |/hello.html |12348 |',
'|2019-03-03 13:00:00UTC |/hello.html |12349 |',
''
]

所以我需要过滤这些日期戳 2019-03-01 10:00:00UTC - 2019-03-02 11:00:00UTC

是否需要用松"|"分割数组以及在那之前?

我该如何解决这个问题?

请尝试一下。

let res = [
'|datestamp              |endpoint    |id    |',
'|2019-03-01 09:00:00UTC |/co.html    |12345 |',
'|2019-03-01 09:00:00UTC |/co.html    |12346 |',
'|2019-03-01 10:00:00UTC |/co.html    |12345 |',
'|2019-03-01 10:30:00UTC |/hello.html |12347 |',
'|2019-03-01 11:00:00UTC |/co.html    |12347 |',
'|2019-03-02 11:00:00UTC |/co.html    |12348 |',
'|2019-03-02 12:00:00UTC |/hello.html |12348 |',
'|2019-03-03 13:00:00UTC |/hello.html |12349 |',
''
]
let dates = [];
for(let i=1;i<res.length-1;i++)
{
  let splitedItem = res[i].split('|');
  dates.push(new Date(splitedItem[1].replace("UTC","").trim()));
}
console.log(dates)

现在你有了一个日期数组,你可以用 lambda 表达式查询这个数组。

不,您不需要先拆分数组的元素。您可以从部分字符串中创建 Date() 对象,并将它们与代表开始和结束的 Date() 对象进行比较 date/times:

let mydates = [
'|datestamp              |endpoint    |id    |',
'|2019-03-01 09:00:00UTC |/co.html    |12345 |',
'|2019-03-01 09:00:00UTC |/co.html    |12346 |',
'|2019-03-01 10:00:00UTC |/co.html    |12345 |',
'|2019-03-01 10:30:00UTC |/hello.html |12347 |',
'|2019-03-01 11:00:00UTC |/co.html    |12347 |',
'|2019-03-02 11:00:00UTC |/co.html    |12348 |',
'|2019-03-02 12:00:00UTC |/hello.html |12348 |',
'|2019-03-03 13:00:00UTC |/hello.html |12349 |',
''
]

let startDate = new Date("2019-03-01 10:00:00");
let endDate = new Date("2019-03-02 11:00:00");

let filtered = mydates.filter(d => new Date(d.substr(1, 19)) >= startDate && new Date(d.substr(1, 19)) <= endDate);
console.log(filtered);