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