问题描述
我正在读取一个.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);
,
请尝试一下。
let res = [
'|datestamp |endpoint |id |',''
]
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表达式查询该数组。