javascript - 从数组中过滤日期范围

标签 javascript arrays filter date-range

我正在读取一个 .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

我需要用松树“|”来分割数组吗?在这样做之前也是如此吗?

我该如何解决这个问题?

最佳答案

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

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);

关于javascript - 从数组中过滤日期范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64276092/

相关文章:

javascript - 仅当 Javascript 中不存在时才追加数组元素

asp.net-mvc - MVC 3 - View 内的授权

javascript - 将跟踪的事件与 Google Analytics(分析)中的目标转化或电子商务交易相关联

javascript - 访问div隐藏参数

c# - 按元素长度对字符串数组进行排序

javascript - 循环数组并输出 HTML

haskell - 将 <q> 和 </q> 标签更改为“特定位置的配对”

vba - 在子表单中设置过滤器

javascript - 有没有办法防止数字在 JavaScript 中为负数?

javascript - Three.js - 如何选择灯光/相机