【问题标题】:What would be the proper way to filter by date按日期过滤的正确方法是什么
【发布时间】:2019-03-25 09:37:41
【问题描述】:

我有一个对象数组,其日期字符串格式为2019-03-22T13:36:18.333Z

我很好奇按照过去一天、过去一周、过去一个月和过去一年对这些数据进行排序的最佳做法是什么。

我想在T 拆分然后在- 再次拆分

我也在考虑将日期放入 Date 对象并以这种方式计算出来。

什么是最有活力的?最有效率?等等

const dates = [
  {created_at: '2019-03-22T13:36:18.333Z'}
  {created_at: '2019-05-22T13:36:18.333Z'}
  {created_at: '2019-03-23T13:36:18.333Z'}
  {created_at: '2019-03-24T13:36:18.333Z'}
  {created_at: '2019-01-22T13:36:18.333Z'}
]
const spliteDate = (date, splitBy) => {
  if(splitBy = 'day'){
    return date.split("T")[0].split("-")[1]
  } else if(splitBy = 'month') {
    return date.split("T")[0].split("-")[2]
  } else if(splitBy = 'year') {
    return date.split("T")[0].split("-")[0]
  }
}
dates.filter(date => {
  return splitDate(date, 'month') === Date.now().getMonth()
}

类似的东西

【问题讨论】:

  • 过滤后的输出应该是什么?
  • 日期为当前日期的日、周、月和年。

标签: javascript datetime filter


【解决方案1】:

将字符串转换为日期对象可能是最简单的方法

例如,您有一个字符串格式的日期数组:

const arr = ['2019-03-22T13:36:18.333Z', '2019-03-28T16:36:18.333Z', '2015-05-21T16:36:18.333Z'];

看看你的问题,如果你想在某个日期过滤它,这样做肯定会更短更高效:

const filterByDate = dateFilter => arr.filter(date => new Date(date).getDate() < dateFilter);

filterByDate(25);
// result [ '2019-03-22T13:36:18.333Z', '2019-05-21T16:36:18.333Z' ]

而且,如果您需要多个过滤器,例如按日期和年份过滤,

const filterByDateAndYear = (dateFilter, yearFilter) => arr.filter(date => (new Date(date).getDate() < dateFilter) && (new Date(date).getFullYear() < yearFilter));

filterByDateAndYear(25, 2018);

//result [ '2015-05-21T16:36:18.333Z' ]

【讨论】:

  • 太棒了。我希望用当前日期的日、周、月和年过滤日期。我想我从您的回答中获得了足够的信息,以了解使用 Date 对象会变得多么容易。
  • 不客气!是的,但请随意尝试所有不同的做事方式:)
猜你喜欢
  • 1970-01-01
  • 2020-09-23
  • 2019-12-01
  • 1970-01-01
  • 2015-01-19
  • 1970-01-01
  • 1970-01-01
  • 2011-09-20
  • 1970-01-01
相关资源
最近更新 更多