Home > OS >  Generate week start date, week end date, month week no by using the given date range in javascript
Generate week start date, week end date, month week no by using the given date range in javascript

Time:10-23

I have given a date range as input ie a start date and an end date, I need to construct an array that contains the week No and the week start date, and the week end date as output.

Input:

startDate = "2022-10-21"
endDate = "2022-12-05"

Output:

result = [{
weekNo: "Oct 2022 - Week 4",
weekStartDate: "2022-10-21",
weekEndDate: "2022-10-23"
},
{
weekNo: "Oct 2022 - Week 5",
weekStartDate: "2022-10-24",
weekEndDate: "2022-10-30"
},
{
weekNo: "Oct 2022 - Week 6",
weekStartDate: "2022-10-31",
weekEndDate: "2022-10-31"
},
{
weekNo: "Nov 2022 - Week 1",
weekStartDate: "2022-11-01",
weekEndDate: "2022-11-06"
},
{
weekNo: "Nov 2022 - Week 2",
weekStartDate: "2022-11-07",
weekEndDate: "2022-11-13"
},
{
weekNo: "Nov 2022 - Week 3",
weekStartDate: "2022-11-14",
weekEndDate: "2022-11-20"
},
{
weekNo: "Nov 2022 - Week 4",
weekStartDate: "2022-11-21",
weekEndDate: "2022-11-27"
},
{
weekNo: "Nov 2022 - Week 5",
weekStartDate: "2022-11-28",
weekEndDate: "2022-11-30"
},
{
weekNo: "Dec 2022 - Week 1",
weekStartDate: "2022-12-01",
weekEndDate: "2022-12-04"
},
{
weekNo: "Dec 2022 - Week 2",
weekStartDate: "2022-12-05",
weekEndDate: "2022-12-05"
}];

Based on the start date and end date I need to construct a monthly calendar week no, monthly calendar start date and end date.

My Code:

constructWeekDataForCustomDates(startDate, endDate) {
      let currentDay = moment(startDate).day(), addDays, weekArrayData = [];

      if (currentDay == 0) {
        addDays = 1;
      }
      else if (currentDay == 1) {
        addDays = 0;
      }
      else if (currentDay == 2) {
        addDays = 6;
      }
      else if (currentDay == 3) {
        addDays = 5;
      }
      else if (currentDay == 4) {
        addDays = 4;
      }
      else if (currentDay == 5) {
        addDays = 3;
      }
      else if (currentDay == 6) {
        addDays = 2;
      }

      while(startDate <= endDate){
        weekArrayData.push({
          checkboxName: this.getweekNoOfMonth(startDate),
          checkboxStartValue: moment(startDate).format("YYYY-MM-DD"),
          checkboxEndValue: moment(startDate).add(addDays, 'day').format("YYYY-MM-DD")
        });

        startDate = moment(startDate).add(addDays, 'day').format("YYYY-MM-DD");
        addDays =  6;
      }
      console.log(weekArrayData)
    }
 // Function To get week no based on the date
 getweekNoOfMonth (date) {
    let input = moment(date)
    const firstDayOfMonth = input.clone().startOf('month');
    const firstDayOfWeek = firstDayOfMonth.clone().startOf('week');
  
    const offset = firstDayOfMonth.diff(firstDayOfWeek, 'days');
  
    return Math.ceil((input.date()   offset) / 7);
  }

In my code I am getting wrong output.

CodePudding user response:

Lets try. A few points to notice:

To negate time zone and day time effects, we must compare only the date part without the time. This is done using string comparison of yyyy-mm-dd format.

Rest of the code speaks for itself. I hope I got all the end cases right.

var startDate = "2022-10-21"
var endDate = "2022-12-05"

var result = getAllWeeks(startDate, endDate);
console.log(result)

function getWeekOfMonth(date) {
  var d = new Date(date);
  var p = new Date(date);
  p.setDate(1);
  var week = 1;
  while (p < d) {
    p.setDate(p.getDate()   1)
    if (p.getDay() == 1) {
      week  ;
    }
  }
  return week;
}

function formatDate(date) {
  return (date.toISOString()).split("T")[0];
}

function getWeekEnd(date, maxDate) {
  var p = new Date(date.getTime());
  var month = p.getMonth();
  while (p.getDay() != 0 && p.getMonth() == month && p < maxDate) {
    p.setDate(p.getDate()   1)
  }
  if (p.getMonth() != month) {
    p.setDate(p.getDate() - 1)
  }
  p = new Date(formatDate(p))
  return p;
}

function getMonthName(date) {
  return date.toLocaleString('default', {
    month: 'short'
  });
}

function getAllWeeks(startDate, endDate) {
  var p = new Date(startDate);
  var d = new Date(endDate);

  var result = [];
  while (formatDate(p) <= formatDate(d)) {
    var weekEnd = getWeekEnd(p, d)
    var obj = {
      weekNo: getMonthName(p)   " "   p.getFullYear()   " - Week "   getWeekOfMonth(p),
      weekStartDate: formatDate(p),
      weekEndDate: formatDate(weekEnd),
    }
    result.push(obj);
    p.setDate(weekEnd.getDate()   1);
  }
  return result;
}
.as-console-wrapper {
  max-height: 100% !important
}

  • Related