skip to Main Content

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


  1. Chosen as BEST ANSWER

      
    
         const breakIntoMonths = (startEpoch, endEpoch) => {
          const monthArray = [];
          let currentMonthEpoch = new Date(startEpoch * 1000);
          let endEpochUnix = new Date(endEpoch * 1000);
          while (currentMonthEpoch <= endEpochUnix) {
            const currentMonth = new Date(currentMonthEpoch).getMonth();
            const currentYear = new Date(currentMonthEpoch).getFullYear();
            const startOfMonth = new Date(currentYear, currentMonth, 0).getTime();
            let endOfMonth = new Date(currentYear, currentMonth + 1, 0).getTime();
            if (endOfMonth > endEpochUnix) {
                endOfMonth = endEpochUnix;
            }
            monthArray.push({ start: startOfMonth / 1000, end: endOfMonth /1000 });
            currentMonthEpoch = new Date(currentYear, currentMonth + 1, 1).getTime();
          }
          return monthArray;
        }
        const perMonths = breakIntoMonths(1673676037, 1681887198);
        console.log('months', perMonths);


  2. 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.

    const breakIntoMonths = (startEpoch, endEpoch) => {
      const monthArray = [];
    
      while (startEpoch < endEpoch) {
        const startDate = new Date(startEpoch * 1000);
        const endDate = new Date(startDate.setMonth(startDate.getMonth() + 1));
        const calcEnd = endDate.getTime() / 1000;
    
        let currentEnd = (calcEnd > endEpoch) ? endEpoch : calcEnd;
    
        monthArray.push({
          start: startEpoch,
          end: currentEnd
        });
        startEpoch = currentEnd;
      }
    
      return monthArray;
    }
    
    const value = breakIntoMonths(1673676037, 1681887198);
    console.log(value)

    You can also make use of recursive function and avoid while, for loop

    var monthArray = [];
    
    const breakIntoMonths = (startEpoch, endEpoch) => {
        const startDate = new Date(startEpoch * 1000);
        const endDate = new Date(startDate.setMonth(startDate.getMonth() + 1));
        
        if (startEpoch < endEpoch) {
          const calcEnd = endDate.getTime() / 1000;
          let currentEnd = (calcEnd > endEpoch) ? endEpoch : calcEnd;
          monthArray.push({start: startEpoch, end: currentEnd});
          breakIntoMonths(calcEnd, endEpoch);
        }
      
        return monthArray;
    }
    
    
    const value = breakIntoMonths(1673676037, 1681887198);
    console.log(value)
    
    Login or Signup to reply.
  3. without using for, while, do while 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.

    const breakIntoMonths = (startEpoch, endEpoch) => {
      let res = [];
      // epoch is in seconds, so 30 * 86400 is 30 days
      const thirtyDays = 30 * 86400;
      const toDate = epoch => new Date(epoch * 1000).toUTCString();
      const calc30Days = (start, end) => {
        if (end >= endEpoch) {
          if (endEpoch > start) {
            res.push([`The last bit (not a full period)`, `${start} (${
              toDate(start)})`, `${endEpoch} (${toDate(endEpoch)})`]); 
          }
          return res;
        }
        res.push([`${start} (${toDate(start)})`, `${end} (${toDate(end)})`]);
        return calc30Days(end, end + thirtyDays);
      };
      console.log(`start: ${toDate(startEpoch)}; end: ${toDate(endEpoch)}`);
      return calc30Days(startEpoch, startEpoch + thirtyDays);
    };
    
    console.log(breakIntoMonths(1673676037, 1681887198));
    .as-console-wrapper {
        max-height: 100% !important;
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search