按日期过滤的正确方法是什么 [英] What would be the proper way to filter by date
问题描述
我有一个对象数组,日期字符串的格式设置为 2019-03-22T13:36:18.333Z
I have an array of objects with date strings formatted as so 2019-03-22T13:36:18.333Z
我很好奇,最好的做法是按照过去一天,过去一周,过去一个月和过去一年的顺序对它们进行排序.
I am curious what the best course of action would be to sort these by past day, past week, past month and past year.
我当时想只是在 T
处拆分,然后在-
I was thinking of just splitting at the T
then splitting again at the -
我也在考虑将日期放入Date对象,并以这种方式弄清楚.
I was also considering putting the date into the Date object and figuring it out that way.
最有活力的是什么?最有效?等
What would be the most dynamic? Most efficient? etc.
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()
}
类似的事情
推荐答案
将字符串转换为Date对象可能是最简单的
It is probably the easiest to convert the strings to Date objects
例如,您有一个字符串格式的日期数组:
For instance, you have an array of dates in string format:
const arr = ['2019-03-22T13:36:18.333Z', '2019-03-28T16:36:18.333Z', '2015-05-21T16:36:18.333Z'];
查看您的问题,如果您想按某个日期过滤它,这样做肯定会更短,更有效:
Looking at your question, if you would like to filter it by a certain date, it is definitely much shorter and efficient to do this:
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' ]
并且,如果您需要多个过滤器,例如按日期和年份过滤,
And, if you require multiple filters, for instance filter by date AND year,
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' ]
这篇关于按日期过滤的正确方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!