【问题标题】:typescript how to filter json by date range打字稿如何按日期范围过滤json
【发布时间】:2017-09-22 21:17:11
【问题描述】:

我有一个如下的 json 数据。我正在使用 angular2 typescript 根据日期范围过滤此 json。我正在使用 Moment 格式化日期字符串。我需要针对类的所有属性过滤搜索值。我管理其他属性。我不知道如何过滤日期范围。任何人都可以帮助如何做到这一点?

过滤条件: 从“时刻”导入 * 作为时刻;

export class FilterCriteria {
    public from: string;
    public to: string;
    public searchValue: string;
    constructor() {
        this.from =  moment(new Date()).format('DD/MM/YYYY').toString();
        this.to =  moment(new Date()).format('DD/MM/YYYY').toString();
    }
}

搜索方式:

return this.searchItems
          .map((item) =>
                items.filter(item => item.id === criteria.searchValue
                            || item.time === criteria.searchValue
                            || item.alertType.toLocaleLowerCase().indexOf(criteria.searchValue.toLocaleLowerCase()) > -1
                            || item.source === criteria.searchValue
                            || item.relevantComms.toLocaleLowerCase().indexOf(criteria.searchValue.toLocaleLowerCase()) > -1
                            || item.to.toLocaleLowerCase().indexOf(criteria.searchValue.toLocaleLowerCase()) > -1
                            || item.from.toLocaleLowerCase().indexOf(criteria.searchValue.toLocaleLowerCase()) > -1));

还有json数据:

[
    {
        "from": "Sender",
        "to": "Receiver",
        "source": "Email",
        "id": "861068CM",
        "date": "24/07/17"
    },
    {
        "from": "Sender",
        "to": "Receiver",
        "source": "Email",
        "id": "861068CM",
        "date": "12/07/17"
    },
    {
        "from": "Sender",
        "to": "Receiver",
        "source": "Email",
        "id": "861068CM",
        "date": "09/07/17"
    },
    {
        "from": "Sender",
        "to": "Receiver",
        "source": "Email",
        "id": "861068CM",
        "date": "02/02/17"
    },
]

【问题讨论】:

  • 进出属性的项目是什么类型?它们是日期对象还是时刻对象?
  • from 和 to 是字符串属性。过滤器必须应用于 json 中的日期属性

标签: typescript momentjs angular2-services


【解决方案1】:

我会使用时刻 query methods isBefore 和 isAfter 方法来比较日期。 将FilterCriteria类中from和to属性的类型改为moment类型:

export class FilterCriteria {
    public from: Moment;
    public to: Moment;
    public searchValue: string;
    constructor() {
        this.from = moment(new Date()); 
        this.to = moment(new Date());
    }
}

然后在过滤器中使用它们:

criteria.from.isBefore(item.date) && criteria.to.isAfter(item.date)

【讨论】:

    猜你喜欢
    • 2018-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-05
    • 1970-01-01
    • 2021-05-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多