I have two epoch timestamp startDate and endDate. I want the timestamp to split per month.
for example : if startDate of time stamp is 14th jan and endDate of time stamp is 19march. it should divide the timestamp in 3 parts.
14th jan to 14th feb (30 days)
14th feb to 14th mar. (30 days)
14th mar to 19 mar. (30 days)
and all the values should be an array of epoch timestamp
without using for, while, do while loop
epoch timestamp :
I/p :
startDate : 1673676037
endDate: 1681887198
const breakIntoMonths = (startEpoch, endEpoch) => {
const monthArray = [];
let currentMonthEpoch = startEpoch;
while (currentMonthEpoch <= endEpoch) {
const currentMonth = new Date(currentMonthEpoch).getMonth();
const currentYear = new Date(currentMonthEpoch).getFullYear();
const startOfMonth = new Date(currentYear, currentMonth, 1).getTime();
let endOfMonth = new Date(currentYear, currentMonth + 1, 0).getTime();
if (endOfMonth > endEpoch) {
endOfMonth = endEpoch;
}
monthArray.push({ start: startOfMonth, end: endOfMonth });
currentMonthEpoch = new Date(currentYear, currentMonth + 1, 1).getTime();
}
return monthArray;
}
const value = breakIntoMonths(1673676037, 1681887198);
console.log(value, 'value')
3
Answers
You can achieve this using below code.
Here we convert the Epoch which is in seconds from Jan. 1, 1970 to date timestamp by multiplying it to 1000. After getting date we used setMonth method and add 1 to it to get next month. Finally we check if the new end is within specified end bound.
You can also make use of recursive function and avoid while, for loop
In that case: use a recursive function. Something like (added dates are for demo):
If you want to split into real months (so, not 30 days), see this Stackblitz snippet.