首页 > 解决方案 > 在 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

标签: javascriptjquerystringtypescriptdate

解决方案


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


推荐阅读