I am currently working on a dropdown filter that lets the user choose between a period of time in where he can select either daily, weekly, monthly and yearly. I manage to create the daily filter but on the weekly, monthly and yearly bases I am having issues with the start and end date that I need to consider each for each loop.
As a sample, let say that I have this object.
let objArr = [ '2022-10-17 00:00:00', '2022-10-24 00:00:00', '2022-11-07 00:00:00', '2022-11-14 00:00:00' ]
So after going through each date, I want to create a range that includes the start date and an end date before the next element. Here is an example of what I am trying to get.
let objArr = [ '2022-10-17 00:00:00'-'2022-10-23 00:00:00', '2022-10-24 00:00:00'-'2022-11-06 00:00:00', '2022-11-07 00:00:00'-'2022-11-13 00:00:00', '2022-11-14 00:00:00'-'2022-11-20 00:00:00' ]
In summary, I want to create a date range for each date element in an object that has gaps in between. I will be using the created date range of each loop to fetch the data from the db that is inside the date range. Thank you in advance
I have no idea what to do here.
Advertisement
Answer
What I would go for, is to compute daily/weekly/monthly/yearly ranges. Your select values would be daily/weekly/monthly/yearly and according to the selected value, you would use the corresponding range to filter information
// Below code might be used with start time included and end time excluded // Also it assumes that taking the user locale is fine (basically someone living in the US might have different results than someone leaving in Asia), and that daily means current day, weekly means current week starting from Monday and ending on Sunday, monthly means current month and yearly means current year. If your notion of daily/weekly/monthly/yearly means last 24hours/7days/30days/365days some tweaking will be needed function getDailyRange() { const date = new Date(); const start = new Date(date.getFullYear(), date.getMonth(), date.getDate()); const end = new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1); return {start, end} } function getWeeklyRange() { const date = new Date(); // assuming you want your week to start with Monday const weekStart = date.getDate() - date.getDay() + 1; const weekEnd = weekStart + 7; const start = new Date(date.getFullYear(), date.getMonth(), weekStart); const end = new Date(date.getFullYear(), date.getMonth(), weekEnd); return {start, end} } function getMonthlyRange() { const date = new Date(); const start = new Date(date.getFullYear(), date.getMonth()); const end = new Date(date.getFullYear(), date.getMonth() + 1); return {start, end} } function getYearlyRange() { const date = new Date(); const start = new Date(date.getFullYear()); const end = new Date(date.getFullYear() + 1); return {start, end} } console.log(getDailyRange()) console.log(getWeeklyRange()) console.log(getMonthlyRange()) console.log(getYearlyRange())