javascript - 在 Javascript 中过滤日期
问题描述
我正在尝试过滤包含大于特定日期的日期(从字符串转换)的数组。
_this.downloadData.forEach(_d => _d.LogTime = _d.LogTime.toString());
console.log(_this.downloadData.filter(x=>new Date(x.LogTime) > new Date('3/11/2019 7:29:12 AM')));
但是过滤器总是返回零个项目
.
数组如下所示:
[0 … 99]
0:
CPUStat:""
Connectivity:""
DiskStatus:""
HostName:"HOSTname"
LastRebootStatus:null
LogTime:"Mon Mar 11 2019 07:39:12 GMT+0530 (India Standard Time)"
__proto__:
Object
解决方案
Most of your problem here consist of the date time format not being ISO 8601 compliant. Because of this you need to clean up the date. LogTime.substring(4,23) + obj.LogTime.substring(28,33)
will get the important parts from your string. Then you can use moment.js
(https://momentjs.com), which is a must for handling time in JavaScript.
You can run the code below and see that it works
// Your example time array
let timeArray = [
{ LogTime:"Mon Mar 11 2019 07:39:12 GMT+0530 (India Standard Time)" },
{ LogTime:"Mon Mar 11 2019 08:39:12 GMT+0530 (India Standard Time)" },
{ LogTime:"Mon Mar 11 2019 09:39:12 GMT+0530 (India Standard Time)" },
{ LogTime:"Mon Mar 11 2019 10:39:12 GMT+0530 (India Standard Time)" }
],
format = "MMM MM YYYY HH:mm:ssZ",
shouldBeAfter = moment('Mar 11 2019 09:00:12+0530', format),
result,
filterDateGreaterThan = function (obj){
let sDate,
mDate;
sDate = obj.LogTime.substring(4,23) + obj.LogTime.substring(28,33);
mDate = moment(sDate, format);
// console.log(mDate);
return mDate.isAfter(shouldBeAfter);
};
result = timeArray.filter(filterDateGreaterThan);
console.log(result);
<script src="https://momentjs.com/downloads/moment.min.js"></script>
Code when not using Moment.js
// Your example time array
let timeArray = [
{ LogTime:"Mon Mar 11 2019 07:39:12 GMT+0530 (India Standard Time)" },
{ LogTime:"Mon Mar 11 2019 08:39:12 GMT+0530 (India Standard Time)" },
{ LogTime:"Mon Mar 11 2019 09:39:12 GMT+0530 (India Standard Time)" },
{ LogTime:"Mon Mar 11 2019 10:39:12 GMT+0530 (India Standard Time)" }
],
shouldBeAfter = new Date('Mar 11 2019 09:00:12+0530'),
result,
filterDateGreaterThan = function (obj){
let sDate,
date;
sDate = obj.LogTime.substring(4,23) + obj.LogTime.substring(28,33);
date = new Date(sDate);
return date.valueOf() > shouldBeAfter.valueOf();
};
result = timeArray.filter(filterDateGreaterThan);
console.log(result);
推荐阅读
- node.js - 如何将 node 模块中的 typescript 命名空间添加到全局命名空间?
- java - 无法取消引用 QueryParser 短
- html - 滚动 inst 上的固定标题在角度应用程序中正常工作
- php - 无法在窗口 7 上的 apache 2.4 上为 php 7.2 安装 xdebug
- php - Wordpress get_template_directory_uri() 不返回 https 而只返回 http
- docker - Docker 容器中的 Spring Boot 资源
- java - 在 main 方法之后没有执行下一个方法
- java - 注释处理器自 java9 以来不工作
- nlog - NLog - 使用最终/黑洞的过滤器
- ios - iOS 11UICollectionView 滚动到顶部卡住了大标题