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.
I was thinking of just splitting at the T
then splitting again at the -
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()
}
Something along these lines
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' ]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.